How to set up a cron job for a specific time and date?

Better Stack Team
Updated on May 4, 2022

Cron is a command-line job scheduler on Unix-like systems. It allows you to run automated tasks in the background and it's especially useful for repetitive jobs.

Those tasks are called cron jobs. Each job consists of three parts. The time when the job should be executed, a user who will run the task, and valid shell command or script that will be executed.

Cron jobs are defined in files called crontabs. Each user can have its own crontab file and there is also a system-wide crontab.

In this quick tutorial, we will take a look at how to set up a cron job to run at a specific time.

Crontab syntax

As mentioned in the introduction, crontabs are files where cron jobs are defined. Those files have simple but strict syntax rules. To create new or edit your crontab run the following command:

crontab -e
Copied!

Every crontab file has to:

  • Start whit a correct cron schedule (can be an environmental variable) or comment on every line
  • Contain a username for each cron job (applies only for system crontab)
  • Contain valid and executable shell expression
  • End with a newline
# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# |  |  |  |  |
# *  *  *  *  *   command to be executed
*  *  *  *  *     echo 'Hello world!'
Copied!

You can use certain operators to specify the time:

  • * is used as any value
  • - is used to state the range of values (e.g. 1 - 5)
  • , is used to specify multiple values
  • / is used to specify step values that can be used in conjunction with ranges (e.g. 1-10/2 is the same as 1,3,5,7,9)

Here are some examples:

At 4:05 on Sunday

5 4 * * sun echo 'Hello world!'
Copied!

Every 5 minutes

*/5  * * * * echo 'Hello world!'
Copied!

At 4:00 on every day-of-month from 8 through 14

0 4 8-14 * * echo 'Hello world!'
Copied!
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack