Cron reference
What is Cron?
Cron is a Unix program that helps you schedule tasks to be executed periodically (e.g., every hour or every 15 minutes). It’s very useful for performing system administration tasks like backing up databases or cleaning up the hard drive.
Jobs scheduled by Cron are known as Cron jobs. These jobs are managed in a special file known as a crontab. Each user on a Unix system can have their own crontab to manage user-specific jobs.
Crontabs usually live under /var/spool/cron/crontabs
. So if we have a user named john, then john’s cron tasks will reside in /var/spool/cron/crontabs/john
.
Cron task syntax
Cron task are scheduled using a special syntax that consists of two parts:
- Schedule: controls when the task should run (e.g., hourly or daily)
- Command: the actual command to perform the task; this can be any command you can run from the command line such as
mysqldump
.
The schedule part forms all the values before <command
> as seen below:
<minute> <hour> <day_of_month> <month> <day_of_week> <command>
Field | Allowed values |
---|---|
minute | 0-59 |
hour | 0-23 |
day_of_month | 1-31 |
month | 1-12 or JAN-DEC |
day_of_week | 0-6 or SUN-SAT |
Example cron task
Install postfix
Cron sends the cron tasks’ output (stdout or stderr) via local mail. You need an MTA (Mail Transfer Agent) to configure the local mail. postfix
is a popular MTA that does the job:
sudo apt install postfix
During the installation process, you’ll be asked what default configuration you want to use. Select the local only
option.
Add cron task
Open your cron tab:
crontab -e
Add the following cron task:
*/1 * * * * echo "Hello, the time is: $(date --iso-8601=seconds)"
Save and exit crontab.
View cron output
Make sure the cron daemon is running:
sudo systemctl status cron
If it’s shown to be Inactive
, then run:
sudo systemctl start cron
Now, you can tail the /var/mail/<your_username>
file to view the output of your cron task:
tail -f /var/mail/<your_username>
You should see something like:
Hello, the time is: 2021-04-19T15:00:01+01:00
More examples of cron tasks
The following task will make a curl request to http://google.com
every Tuesday at 5.30 PM. You can use the Crontab Guru tool to validate and understand different cron expressions.
30 17 * * 2 curl http://www.google.com
Here are some more examples:
# Every Tuesday, Wednesday, and Thursday at 4:00 AM
0 4 * * 2-4
# Every day at 4:00 AM
0 4 * * *
# Every 15 minutes
*/15 * * * *
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment