Scheduling Tasks with Cron

Cron is a time-based job scheduling daemon found in Unix-like operating systems, including Linux. It enables users to schedule jobs (commands or scripts) to run periodically at fixed times, dates, or intervals. These scheduled jobs are known as cron jobs.

Crontab (Cron Table) is a configuration file that specifies the schedule of cron jobs. It contains commands to be executed along with their scheduled times. Each user on a system can have their crontab file, typically at /var/spool/cron/crontabs/, and there is also a system-wide crontab at /etc/crontab.

How 'cron' Works

Under the hood, the cron system is relatively simple yet powerful, and it operates by regularly checking for scheduled tasks and executing them at the specified times.

The algorithm used by cron is as follows:

  1. On start-up, the cron daemon (crond) looks for the crontab files.

  2. For each crontab file found, determine the next time in the future that each command must run.

  3. Place those commands on the event list with their corresponding time and their "five field" time specifier.

  4. Enter main loop:

    1. Examine the task entry at the head of the queue, and compute how far in the future it must run.

    2. Sleep for that period of time.

    3. On awakening and after verifying the correct time, execute the task at the head of the queue (in the background) with the privileges of the user who created it.

    4. Determine the next time in the future to run this command and place it back on the event list at that time value.

Understanding Crontab Format

The crontab file is composed of lines of comments and cron jobs and looks as follows:

Comments begin with a comment mark #, and must be on a line by themselves.

The syntax of a cron job line in a crontab file must use the following format:

MIN HOUR DOM MON DOW CMD

The first five fields, each separated by a single space, represent time intervals and tell Cron when to initiate the cron job. These fields are followed by the command (CMD), which is usually a path to a script or a system command.

Cron expression examples:

SyntaxDescription
7 * * * *The cron job is initiated every time the system clock shows 7 in the minute's position.
0 7 * * *The cron job runs any time the system clock shows 7 AM (7 PM would be coded as 19).
0 0 7 * *The Day of the Month is 7, which means that the job runs every 7th day of the month.
0 0 0 7 *The numerical Month is 7, which determines that the job runs only in July. The Month field value can be a number or a month abbreviation.
0 0 * * 77 in the current position means that the job would only run on Sundays. The Day of the Week field can be a number or the day abbreviation.
0 9-17 * * 1-5Hyphens are used to define ranges. For example, place 9-17 in the Minutes field and 1-5 in the Day of the Week field for a job to run from Monday to Friday - Every Hour 9 AM to 5 PM.
0 4 * * 2,4Commas are used to separate items of a list. For example, to run a job at 4 AM on Tuesdays and Thursdays, place 2,4 in the Days of the Week column.
* /20 * * *Slashes can be combined with ranges to specify step values. For example, */20 in the Minutes field runs a job every twenty minutes.

Nonstandard predefined scheduling definitions:

Some cron implementations support the following non-standard macros:

SyntaxEntryDescription
0 0 1 1 *@yearly (or @annually)Run once a year at midnight of 1 January
0 0 1 * *@monthlyRun once a month at midnight of the first day of the month
0 0 * * 0@weeklyRun once a week at midnight on Sunday
0 0 * * *@daily (or @midnight)Run once a day at midnight
0 * * * *@hourlyRun once an hour at the beginning of the hour
@rebootRun at startup

Crontab Commands

  1. To edit your crontab file, run:

     crontab -e
    
  2. To list your current cron jobs, run:

     crontab -l
    
  3. To remove your crontab file, run:

     crontab -r
    
  4. To edit another user's crontab (requires superuser privileges), run:

     sudo crontab -u username -e
    
    💡
    The direct editing of user crontab files in /var/spool/cron/crontabs/ is typically restricted to the system's cron service and should not be edited manually. Permissions are set to prevent unauthorized access. For managing cron jobs, the crontab utility provides a safe and standardized way for users to edit their cron schedules.

Examples of Cron Jobs

  1. To run a script every Monday at 6:30 AM:

     30 6 * * 1 /path/to/script.sh
    
  2. To delete temporary files every hour:

     0 * * * * /bin/rm -rf /tmp/*
    
  3. To check disk space usage and email the results every Sunday at 7 PM:

     0 19 * * 0 df -h | mail -s "Disk Space Report" user@example.com
    

Tips for Writing Cron Jobs

  1. Specify full paths to files and programs because cron jobs run in a limited environment, meaning that many of the environmental variables available in a full-user session might not be present. Also, it helps to prevent accidental or malicious execution of the wrong program.

  2. By default, cron sends the output of jobs via email to the user's account. If you don't want this, redirect the output to a file or /dev/null.

  3. Before setting up a cron task, run your script or command to see if you have any problems with permissions or paths.

  4. If too many jobs run at the same time — especially the backups and compiles —the system would run out of RAM and nearly fill the swap file. As a result, the system thrashes and the performance decreases, so nothing gets done. In such a case, add more memory and improve how tasks are scheduled.

  5. Remove a task that is poorly written and use large amounts of memory.

The crond service assumes that the host computer runs all the time. That means that if the computer is turned off during a period when cron jobs were scheduled to run, they will not run until the next time they are scheduled. This might cause problems if they are critical cron jobs. Fortunately, there is another option for running jobs at regular intervals: anacron.

anacron

The anacron program performs the same function as crond, but it adds the ability to run skipped jobs, such as if the computer was off or otherwise unable to run the job for one or more cycles. This is very useful for laptops and other computers that are turned off or put into sleep mode.

As soon as the computer is turned on and booted, anacron checks to see whether configured jobs missed their last scheduled run. If they have, those jobs run immediately, but only once (no matter how many cycles have been missed). For example, if a weekly job did not run for three weeks because the system was shut down while you were on vacation, it would be run soon after you turn the computer on, but only once, not three times.

References:

  1. Linux Crash Course - Scheduling Tasks with Cron

  2. Wikipedia: cron

  3. How I use cron in Linux

  4. How to schedule jobs using the Linux 'cron' utility

  5. How to Create and Set Up a Cron Job in Linux