Certainly! Here’s a tutorial on using cron jobs, a time-based job scheduler in Unix-like operating systems.
Step 1: Understanding Cron
- Cron is a utility that allows you to schedule and automate recurring tasks on your system.
- Cron jobs are defined using a special syntax called cron expressions, which specify when and how often a task should run.
- Each cron job is associated with a command or script that will be executed at the specified time.
Step 2: Accessing the Cron Tab
- Open a terminal or SSH into your server.
- Enter the following command to edit the cron tab:
crontab -e
This will open the default text editor for editing the cron tab.
Step 3: Creating a Cron Job
- In the cron tab file, each line represents a separate cron job.
- The basic structure of a cron job is as follows:
* * * * * command_to_be_executed
The five asterisks represent the schedule for the job (minute, hour, day of month, month, day of week).
- Specify the desired schedule using the cron expressions. For example:
-
*
indicates any value or all possible values. -
*/5
means every 5 units (e.g., every 5 minutes). -
1,2,3
means the specific values 1, 2, and 3. - Ranges can be specified using a hyphen (e.g.,
1-5
for 1, 2, 3, 4, 5). - You can use special shortcuts like
@reboot
(runs once at startup) or@daily
(runs once per day at midnight).
-
- After specifying the schedule, provide the command or script you want to run at that time.
Step 4: Saving and Exiting
- Once you’ve defined your cron job, save the file and exit the editor.
- In Vim, press
Esc
to exit insert mode, then type:wq
and pressEnter
. - In nano, press
Ctrl+O
to save andCtrl+X
to exit.
- In Vim, press
- The cron tab will be automatically updated, and the cron daemon will take care of executing the scheduled jobs.
Step 5: Managing Cron Jobs
- To list all your scheduled cron jobs, use the following command:
crontab -l
- To edit your existing cron jobs, use:
crontab -e
This will open the cron tab file for editing.
- To remove all your cron jobs, use:
crontab -r
Be careful when using this command, as it permanently deletes all your cron jobs.
Step 6: Handling Output and Errors (Optional)
- By default, the output generated by a cron job is sent via email to the user who owns the cron job.
- To redirect the output to a file, modify the cron job entry to include the redirection. For example:
* * * * * command_to_be_executed > /path/to/output_file.log 2>&1
This redirects both standard output and error output to the specified file.
- Make sure the user running the cron job has write permissions to the output file.
That’s it! You now have the basic knowledge to create and manage cron jobs. Use cron to automate repetitive tasks and make your system more efficient.
About the author. Geoffrey Callaghan is a programmer at fabform.io working on the form backend team.