Issue:
How to setup cron jobs in Ubuntu (and Linux)?
Solution:
Setting up cron jobs on a Linux system like Ubuntu is a straightforward process. Cron jobs are scheduled tasks that your system runs at specified times or intervals. Here’s how you can set them up:
Accessing the Cron Table:
- Open the Terminal: Launch your terminal application.
- Edit Cron Jobs for Your User: To edit the cron jobs for your current user, use the following command:
crontab -e
This command opens your user’s cron file in the default text editor. If it’s your first time usingcrontab
, it may ask you to select an editor (likenano
,vi
, etc.). - Add a New Cron Job: In the text editor, you can add a new cron job in the following format:
* * * * * command-to-execute
This is broken down as:Minute (0 - 59)
Hour (0 - 23)
Day of the month (1 - 31)
Month (1 - 12)
Day of the week (0 - 6) (Sunday = 0)
0 5 * * * /path/to/script.sh
Make sure your script (script.sh
in this example) is executable. You can make it executable withchmod +x /path/to/script.sh
. - Save and Exit: After adding your cron job, save and exit the editor. This will install the new cron job.
- Verify Your Cron Jobs: To ensure your cron job is listed, use:
crontab -l
Special Syntax:
Instead of the asterisks, you can use special strings for common intervals:
@reboot
: Run once, at startup.@yearly
or@annually
: Run once a year, “0 0 1 1 *”.@monthly
: Run once a month, “0 0 1 * *”.@weekly
: Run once a week, “0 0 * * 0”.@daily
: Run once a day, “0 0 * * *”.@hourly
: Run once an hour, “0 * * * *”.
Common Examples:
- Backup Every Day at Midnight:
0 0 * * * /path/to/backup/script.sh
- Run a PHP Script Every Hour:
0 * * * * /usr/bin/php /path/to/your/script.php
Tips:
- Environment Variables: Cron jobs run in a minimal environment, so you might need to define environment variables that your task requires.
- Output Handling: By default, cron sends the output of the job to the user’s mail (local mail, not internet email). You can redirect the output to a file or to
/dev/null
if you don’t need it. - Logging: To log the output of a cron job, redirect the output to a file:
* * * * * command-to-execute >> /path/to/logfile 2>&1
- Script Permissions: Ensure that any scripts you’re calling are executable and have the appropriate permissions.
Cron jobs are particularly useful for automating routine tasks like backups, system updates, or periodic cleanup of temporary files.