Cron Job Tutorial

A cron job is a scheduled task or job on Unix-like operating systems. The term cron comes from the Greek word "chronos," which means time. Cron jobs are used to automate repetitive tasks by scheduling them to run at specific intervals. These tasks can range from simple operations, like running a script to perform backups, to more complex operations such as updating databases or sending emails.


Cron Job Syntax

*   *   *   *   *  /usr/bin/bash /path/to/script/script.sh
|   |   |   |   |              |
|   |   |   |   |      Command or Script to Execute
|   |   |   |   |
|   |   |   |   |
|   |   |   |   |
|   |   |   |   Day of the Week(0-6)
|   |   |   |
|   |   |   Month of the Year(1-12)
|   |   |
|   |   Day of the Month(1-31)
|   |
|   Hour(0-23)
|
Min(0-59)

Here

Position Time Value Description

1

Minutes

0-59

Command would be executed at the specific minute.

2

Hours

0-23

Command would be executed at the specific hour.

3

Days

1-31

Commands would be executed in these days of the months.

4

Months

1-12

The month in which tasks need to be executed.

5

Weekdays

0-6

Days of the week when commands would run.

  • Sunday (0)

  • Monday (1)

  • Tuesday (2)

  • Wednesday (3)

  • Thursday (4)

  • Friday (5)

  • Saturday (6)


Cron Job Useful Operators

  • Asterisk (*) : This operator signifies all possible values in a field.

    • Example: Write * (asterisk) in the Minute field to make the cron job run every minute.


  • Comma (,) : Used to specify a list of values.

    • Example: Writing 1,5 in the day-of-week field will schedule the job to run every Monday and Friday.


  • Hyphen (-) : Denotes a range of values.

    • Example: Write 6-9 in the Month field to set up a cron job from June to September.


  • Forward Slash (/) : This separator divides a value.

    • Example: Run a script every twelve hours, write */12 in the Hour field.


  • Last (L) : Users can use this operator in the day-of-month and day-of-week fields.

    • Example: Writing 3L in the day-of-week field means the last Wednesday of the month.


Cron Job Useful Commands

  • crontab -e : Edits crontab entries to add, delete, or edit cron jobs.

  • crontab -l : List all the cron jobs for the current user.

  • crontab -u username -l : List another user’s cron.

  • crontab -u username -e : Edit another user’s cron.


Cron Job Examples

Perform a backup every Monday at midnight.

0 0 * * 1 /root/backup.sh

Clear the cache every hour on Monday.

0 * * * 1 /root/clearcache.sh

Backup data twice a day at 6 am and 6 pm.

0 6,18 * * * /root/backup.sh

Perform monitoring every 10 minutes

*/10 * * * * /scripts/monitor.sh

Clear the cache on the first day of every month at 2:15 pm.

15 14 1 * * /root/clearcache.sh

Run the monitoring script once a day at midnight.

0 0 * * * /scripts/monitor.sh

Clear the cache at midnight on the 15th of every month.

0 0 15 * * /root/clearcache.sh