How to Schedule Cron Jobs/Tasks in Linux/Unix

|
Last Updated:
|
|

Today, we are going to learn how to schedule cron jobs/tasks in Linux/Unix.

Well, in Linux, most of the system administration tasks, aka jobs ,are done repeatedly. These tasks do not happen at the same time in most cases. In order to save time of having to run similar tasks over and over again, Linux/Unix provides tools that can be used to automate these tasks by scheduling them to run at specific times without human interaction.

This guide will cover automating regular tasks using cron jobs.

Schedule Tasks in Linux Using cron

Cron is a service that is used to schedule cron jobs/tasks in Linux/Unix. Cron jobs are tasks that are executed at regular time intervals on systems that are rarely shut down.
It reads various configuration files for cron jobs also known as cron table files or simply crontab files. These include;

  • Files in /var/spool/cron/crontabs directory that are named after user accounts in /etc/passwd.
    • crontabs in this directory should only be edited and updated using the crontab command.
  • /etc/crontab
    • In Debian based systems, the cron jobs defined on the /etc/crontab file are predefined to run programs under /etc/cron.hourly/etc/cron.daily/etc/cron.weekly and /etc/cron.monthly.
  • Cron also reads files in the /etc/cron.d directory.

/etc/crontab and the files in /etc/cron.d must be owned by root, and must not be group or other-writable.

The role of the cron, therefore, is to check in every minute the commands defined on the crontabs to see if it should be run in the current minute.

Once executed, the output of the crontab commands is mailed to the owner of the crontab or to the user named in the MAILTO environment variable in the crontab.

Types of Cron Jobs

There are two types of cron jobs;

  • User cron jobs
  • System cron jobs

User cron jobs

  • These are the cron jobs that are created by the normal users for running user programs or tasks. User cron jobs can also be created as root user.
  • They are controlled using the crontab utility.

System cron jobs

  • They cron jobs that are run as root and are used to perform system-wide maintenance tasks. For example the cron jobs that are used to clean the /tmp directory.
  • They are controlled by the /etc/crontab file or files in /etc/cron.d/ directory.

So how are cron jobs created? Let us see how to create cron jobs as an ordinary system user and as a root user.

Scheduling System cron Jobs

System cron jobs are run as root user.

Open the /etc/crontab file.

vim /etc/crontab

The first few uncommented lines in this file may define environment variables, such as;

  • $PATH which sets the system path
  • $SHELL which defines the shell to be used when executing jobs
  • $MAILTO which sets the address to which cron job output is mailed.

See a sample /etc/crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# 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
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

The crontab consists of six or seven fields that describe details of the schedule.

  • The first five fields define the time to execute a cron job. This is arranged in the following order;
    • Minute of the hour (0–59)
    • Hour of the day (0–23) in 24HR clock system, aka military time.
    • Day of the month (1–31)
    • Month of the year (1–12). You can use the number of the month or simply the first three letters of the name of the month.
    • Day of the week (0–7). 0 and 7 represents Sunday.
  • The sixth field defines the user account to use executing the cron job commands.
  • The seventh field defines the commands and any associated options to be executed.

While defining the time, below are the possible values tjhat can be used;

  • Asterisk (*) can be used to specify all possible values. For example, * on the first field means every minute
  • Specify different values by separating them with comma (,). For example to schedule a cron job to run at minute 1, 15, and 30 use 1,15,30 in the minute field.
  • Specify a range of values using dash (-). For example, to run a job between 8 PM and 10 PM use, 20-22 in the hour field.
  • Specify step values using the forward slash (/). For example to run a job every 5 minutes, use */5 in the minute field.

Examples

Run a task every midnight

Assume you have a script that performs a specific task that needs to be executed every midnight, enter the line;

0 0 * * * /path/to/the/myscript.sh
Run a task every minute
* * * * * /path/to/the/myscript.sh
Run a script after every 5 minutes between 10-11 PM
*/5 22-23 * * * /path/to/the/myscript.sh
Run the script at 6 PM every Friday
* 18 * * */5 /path/to/the/myscript.sh
Run a script in every minute in every February, March, April
* * * Feb,Mar,Apr * /path/to/the/myscript.sh

Schedule Cron Jobs as normal user

A non-root system user can schedule cron jobs using the crontab command. This command is used to maintain crontab files for individual users. It installsdeinstalls or lists the tables that are read by cron.

The command line syntax for crontab command is;

crontab [ -u user ] file
crontab [ -u user ] [ -i ] { -e | -l | -r }
  • The -u option specifies the name of the user whose crontab is to be used or modified.
  • the -i option can be used with -r option for interactive prompt when removing a cron job.
  • The -r option is used to remove a cron job
  • The -l option displays the contents of the current cron table.
  • The -e option is used to edit the current cron table.

Controlling access to cron

A user can be allowed or denied to schedule cron jobs based on the /etc/cron.allow or /etc/cron.deny files if at all they exist.

A user listed in /etc/cron.allow is allowed to execute the job while users listed in /etc/cron.deny are not allowed to execute the job.
Users can be listed one user per line in these files.
Note that ff neither cron.allow nor cron.deny exists, superuser privileges are required to run the crontab command.

Examples

To create a cron job on your home directory that executes a specific script every 6:00 AM on every Wednesday, Thursday and Friday and mail the output to you. Create a file on your home directory with the content below;

Replace myloginname with your login username.

vim ~/mycronjobs
MAILTO=myloginname
6 * * 3,4,5 ~/myscript.sh 

To install the cron job, simply run;

crontab mycronjobs

To list the installed cron jobs;

crontab -l
* * * 3,4,5 ~/myscript.sh 

When run with no option, crontab will install new cron jobs overriding the existing.

To edit the existing cron job, simply use option -e and add new jobs.

crontab -e

Add new jobs, save and quit the file. You can list the jobs again.

* * * * 3,4,5 ~/myscript.sh
*/10 * * * */5 ~/my-another-script.sh

Not that user cron jobs do not include usernames unless you have the rights to execute other user’s cron jobs.

Editing system crontab as a normal user

As a normal user, you can be able to edit or update the system crontabs (crontabs owned by the root user) using sudo rights. For example to edit the root user crontab;

sudo crontab -e

To list root user cron jobs;

sudo crontab -l

In case you want to edit other user cron jobs as non-root user, ensure that you have the sudo privileges. For example, to edit the cron jobs for the user john,

sudo crontab -u john -e

To list the cron jobs for the user john;

sudo crontab -u john -l

Scheduling Cron Jobs Hourly, Daily, Weekly, Monthly

If you need to schedule your jobs on hourlydailyweeklymonthly … basis, simply place either the individual script or commands that executes your tasks on the following directories respectively;

  • /etc/cron.hourly/
  • /etc/cron.daily/
  • /etc/cron.weekly/
  • /etc/cron.monthly/

Note that the cron jobs scheduled in this way can however be defined on cron tables using special strings that replaces the first five time fields. as illustrated below;

  • Hourly cron jobs
    • Hourly cron jobs are tasks that can executed once every hour and can be represented using the string @hourly
    • In time field format, this would be represented as 0 * * * *
    • For example;
      @hourly /path/to/myscript.sh
  • Daily/Midnight cron jobs
    • Daily/Midnight cron jobs are tasks that can executed once a day and can be represented using the string @daily or @midnight.
    • In time field format, this would be represented as 0 0 * * *.
    • For example;
      @daily /path/to/myscript.sh or
      @midnight /path/to/myscript.sh
  • Weekly cron jobs
    • Weekly cron jobs are tasks that can executed once a week and can be represented using the string @weekly.
    • In time field format, this would be represented as 0 0 * * 0.
    • For example;
      @weekly /path/to/myscript.sh
  • Monthly cron jobs
    • Monthly cron jobs are tasks that can executed once a month and can be represented using the string @monthly.
    • In time field format, this would be represented as 0 0 1 * *.
    • For example;
      @monthly /path/to/myscript.sh
  • Yearly/Annually cron jobs
    • Yearly/Annually cron jobs are tasks that can executed once a year and can be represented using the string @yearly or @anually.
    • In time field format, this would be represented as 0 0 1 1 *.
    • For example;
      @yearly /path/to/myscript.sh or
      @annually /path/to/myscript.sh
  • System Startup cron jobs
    • System startup cron jobs are tasks that can executed once at system startup. They can be represented using the string @reboot.
    • For example;
      @reboot /path/to/myscript.sh

To check the validity of your cron job time, use the cron schedule expression editor.

That is all on our guide on how to schedule cron jobs/tasks in Linux/Unix. This topic is a bit wider and examples covered in here a just but a drop in the ocean. Feel free to drop your comments.

Read more on man crontab.

You can also utilize the Crontab Generator.

See our other guides on scheduling non-regular tasks using anacron and at commands.

Scheduling tasks using anacron in Linux/Unix

Scheduling tasks using at command in Linux

SUPPORT US VIA A VIRTUAL CUP OF COFFEE

We're passionate about sharing our knowledge and experiences with you through our blog. If you appreciate our efforts, consider buying us a virtual coffee. Your support keeps us motivated and enables us to continually improve, ensuring that we can provide you with the best content possible. Thank you for being a coffee-fueled champion of our work!

Photo of author
koromicha
I am the Co-founder of Kifarunix.com, Linux and the whole FOSS enthusiast, Linux System Admin and a Blue Teamer who loves to share technological tips and hacks with others as a way of sharing knowledge as: "In vain have you acquired knowledge if you have not imparted it to others".

2 thoughts on “How to Schedule Cron Jobs/Tasks in Linux/Unix”

Leave a Comment