Read in 3 minutes

last updated 

How to create and manage cron jobs

Cron is a scheduling daemon that executes tasks at specified intervals. These tasks are called cronjobs. Cron jobs are mostly used for creating periodic and recurring tasks.

For example, you could set a cron job to backup your databases or data, update your system with the latest security patches, check your disk space usage, sending emails and more.

Crontab Syntax and Operators

Each line in the crontab file contains six fields separated by a space.

* * * * * command(s) to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

A field may contain one or more values, separated by a comma or a range of values separated by a hyphen.

*	any value
,	value list separator
-	range of values
/	step values

Create and Manage Cron Jobs

You can create new cron jobs, as well as view, edit and delete existing cron jobs, using the following command:

crontab -e

Once you run the command above it will open a new screen with existing cron tasks if they exist.

Crontab files are stored in the /var/spool/cron/crontabs directory, with the user’s name as a file name. Although you can edit the file manually, it is recommended to use the crontab utility.

By default the email notification is sent to the owner of the crontab. To overwrite the default behavior you can use the MAILTO environment variable with a list (comma separated) of all the email addresses you want to receive the email notifications. If MAILTO is defined but empty (MAILTO=""), no mail is sent.

Advertisement

Cron Jobs Examples

Below are some examples which will show you how to schedule a cron job to run on different time periods.

  • Run a command at 15:00 on every day from Monday through Friday:

    `cronjob 0 22 * * 1-5 command

  • Run a script every 5 minutes and redirected the standard output to dev null, only the standard error will be sent to the specified e-mail address:

    [email protected]
    */5 * * * * /path/to/script.sh > /dev/null
  • Run two commands every Monday at 3 PM (use operator && between your commands):

    0 15 * * Mon command1 && command2
  • Run a PHP script every 2 minutes and write the output to a file:

    */2 * * * * /usr/bin/php /path/to/script.php >> /var/log/script.log
  • Run a script every day, every hour, on the hour, from 8 AM through 4 PM:

    00 08-16 * * * /path/to/script.sh

Conclusion

You have learned how to create cron jobs and schedule tasks like running backups to execute at a specific date and time.

Feel free to leave a comment if you have any questions.