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 useful for performing admin tasks like backing up databases or cleaning up the hard drive.
Jobs scheduled by Cron are called Cron jobs. These jobs are managed in a special file called a crontab. Each user on a Unix system can have their own crontab to manage user-specific jobs.
Where are the crontab files?
On Linux, the crontab file can usually be found at /var/spool/cron/crontabs
if you have any. So if you have a user named john, then john’s cron tasks can be found at /var/spool/cron/crontabs/john
.
On macOS, they can be found at /var/at/tabs
(if you have any).
You should never edit your crontab files manually and instead use the crontab -e
command to edit them.
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)"
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: Wed Jul 2 18:56:44 BST 2025
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