Global

Product

Doc

Support

SiliCloud Help Document Center

search

Popular search terms:

Using the Cron Task Scheduler on Linux

Update time:2022-12-01 23:58  Version:v1.4
I want feedback 
Collect My collection

Overview

    You can read this guide to use the Cron and Anacron Task Scheduler on various Linux operating systems.


Requirements

      Linux operating system, such as Debian, Ubuntu, and CentOS.

      A user account that has root access or sudo privileges.


Introduction to Cron

    Cron is a command-line utility that allows you to run certain scheduled tasks on Linux operating systems, which include scripts, command lines, and other processes. With Cron, you can manage your tasks easier just by scheduling them, so you don’t need to go through some repetitive tasks on Linux one by one. You can automate various tasks using Cron on Linux, such as system maintenance, backup, file and email downloads, and the use of web scraper tools.

    To use Cron, you will need to activate the background service called the crond daemon on your Linux-based OS. Meanwhile, the actions for the Cron command-line utility will get managed with the crontab files on your Linux OS directory. These crontab files will allow the Cron services to determine which scheduled tasks to perform at which time period.

    You can find the crontab files on various directories on your Linux-based OS, including:

      /var/spool/cron/crontabs. You can’t access this directory via the file manager, but you can access and update this directory via the crontab command.

      /etc/crontab. This directory will belong to the root user with no group- or other-writable.

      /etc/cron.d. Various system services will add their crontab files to this directory.

    The Cron command-line utility will activate every minute to check if there are some scheduled tasks it needs to run. It will also check the spool directory to find out if there are some changes in the modtime values. When there are some changes in the modtime values, it will reload them to keep the Cron services running without restarting them.

    Keep in mind that each user in your Linux-based OS can have their own crontab files.


Understanding the Crontab File Anatomy

    Before executing any cron-related commands, Cron will use a special format that will check the command lines from the crontab configuration files.

# ┌───────────── minute (0 - 59)

# │ ┌───────────── hour (0 - 23)

# │ │ ┌───────────── day of the month (1 - 31)

# │ │ │ ┌───────────── month (1 - 12)

# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;

# │ │ │ │ │                                   7 is also Sunday on some systems)

# │ │ │ │ │

# │ │ │ │ │

# * * * * *  <command to execute>

 

With the format above, each line will represent a different cron job.

 

30  17  7  *  *  /home/user/myscript/do_something.sh

 

    You can add the line like the above to a crontab file to schedule the do_something.sh script to run at 17:30 every 7th day of the month. You will need to add a space to separate each field. Note: Use the * (asterisk) sign to specify different values you would like to assign, depending on the schedule you want to set on a crontab file.

    There are various variables you can use to set up the default environment in the crontab file, such as:

      MAILTO. Use this variable to set the cron job results to a specific email address.

      SHELL. You can use this variable to specify any shell you would like to use.

      PATH. Use this variable to set a specific path you want to use for the environment.

    You need to put these variables at the top position on the crontab file.

SHELL=/bin/bash

[email protected]

PATH=/bin:/sbin:/usr/bin:/usr/sbin

    Please note that you will only give these variables to the current user with the desired values for the default environment, as Cron itself doesn’t provide any kind of environment when you run it.

 

How to Add a Cron Job

    It’s easy to add a cron job. You just need to edit the crontab configuration file designated for the current user. Open the terminal window and enter this command.

$ crontab -e

    You can also add a cron job for a different user. To do it, you need to use the sudo privileges and enter this command in the terminal window.

# crontab -u user_name -e

    After typing this command, you will see this text file popped up.

# Edit this file to introduce tasks to be run by cron.

#

# Each task to run has to be defined through a single line

# indicating with different fields when the task will be run

# and what command to run for the task

#

# To define the time you can provide concrete values for

# minute (m), hour (h), day of month (dom), month (mon),

# and day of week (dow) or use '*' in these fields (for 'any').

#

# Output of the crontab jobs (including errors) is sent through

# email to the user the crontab file belongs to (unless redirected).

#

# For example, you can run a backup of all your user accounts

# at 5 a.m every week with:

# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

#

# For more information see the manual pages of crontab(5) and cron(8)

#

# m h  dom mon dow  command

 

    You just need to add a cron job to the text file with the format as described earlier.

30 17 7 * *  /home/user/myscript/do_something.sh

 

    You can save and close the text editor after adding the cron job command. Congratulations! Now, your new cron job command will be active for the current user. You can check the new cron job you just added by visiting the /var/spool/cron/crontabs directory.

    The cron job will also get delivered to the email address as specified by the crontab owner. You can prevent the cron job from getting delivered to the specified email address by adding the string >/dev/null 2>&1 in the command field like this.

*  *  *  *  *  <command/script-to-execute> >/dev/null 2>&1


    There are also more examples of cron jobs you can add, such as:

      Running command at 3AM, 9AM, and 12PM every day.

0    3,9,12    **     *    <command>

      Running command every hour on December 16th.

0   *   16  12  *   <command>

      Running command 15 minutes past every hour every Sunday, between 12AM to 6AM.

15  0-6 *   *   0   <command>


    You can also use some special strings as shortcuts for your cron jobs, such as:

      @reboot – it will allow the cron jobs to run once at startup.

      @yearly – it will run every year, which is the same as 0 0 1 1 *”.

      @annually – it will run every year.

      @monthly – it will run once per month, such as 0 0 1 * *”.

      @weekly – it will run once per week, such as 0 0 * * 0”.

      @daily – it will run once per day, such as 0 0 * * *”.

      @midnight – it will run daily.

      @hourly – it will run once per hour, such as 0 * * * *”.

    An example of using the shortcut is when you want to run it daily. You can use this command:

@daily  <command-to-execute>


How to List Cron Jobs

    You can also list the cron jobs you have added to your Linux operating system without having to open the crontab configuration files by using this simple command:

$ crontab -l

 

How to Restrict the Cron Access

    Cron jobs can help you automate various tasks in your Linux operating system, but sometimes, it can also get misused by some users. So, as the system administrator, you can restrict the access to cron task scheduler for certain users. To limit the access to the cron jobs, you can create the file at /etc/cron.d/cron.allow, which will contain the list of the users and their permission status to create cron jobs.

    Another way is to create a file at the /etc/cron.d/cron.deny directory, with the list of users you would like to deny their permission to create cron jobs.

    For instance, you can restrict the users willmark and janedoe from creating any cron jobs in your system by creating the file containing their usernames at /etc/cron.d/cron.deny. Here are the simple steps to do it:

      Create a new file at /etc/cron.d/cron.deny and open it.

      Add the lines on the text file like this:

janedoe

willmark

      Next, you can save and close the file.

    By doing this, you will deny the users janedoe and willmark from creating cron jobs in your operating system. However, please note that this method will not affect root users from creating cron jobs.

    With the root privileges, you can deny any regular users from creating cron jobs. However, you can also create cron jobs as the users you have denied by using the sudo/su command, which allows you to log in as those users using your root access privileges. You can use this command to do it:

*  *  *  *  *  <user>  <command/script-to-execute>

    Or, you can also do it another way. You can log in as the user using the root command and use your root privileges to create the cron jobs once you’ve logged into the user’s account.

 

What is Anacron?

    Sometimes, Cron can miss the scheduled jobs it needs to run when the system is shutdown or in sleep mode. When this happens, you might miss on various important automated jobs, such as email or data backup.

    It’s time for you to set up Anacron. Anacron is quite similar to Cron, but its primary purpose is to run the cron jobs that got skipped because of system shutdown or sleep mode. So, Anacron will check whether there are some missing cron jobs you have set up in your system the moment you turn on the system after a shutdown or sleep mode, and then it will run the missed jobs once. Please note that Anacron will only run the missed cron jobs once regardless of how many cycles the cron jobs have missed.

    Anacron uses the special configuration file stored at /etc/anacrontab to check the list of jobs it will control. Each job list will have its own variables, such as period, delay, job identifier, and the shell command.

#period  delay  job-identifier  shell-command

    Period means how many days the job has to run in the system. Delay means how long Anacron needs to wait before running the shell command for the job. And Job Identifier means the name of the job, which will get written in the log file later.

    After executing and exiting the shell command for the job, Anacron will store it with the timestamp file for the job, and then Anacron will execute the job again according to the variable for the job. Keep in mind that Anacron will only use the date variable to execute the job again, not the hours variable.

 

How to Add Jobs to Anacron

    Cron is something that you can access right away in your operating system with no third-party installation. However, for Anacron, you will need to install it just like you would when you install other software on Linux. You can install Anacron on the Ubuntu and Debian system by typing this command on the terminal.

# apt-get update && apt-get install Anacron

    After installing Anacron, you can access the configuration file at /etc/anacrontab, to add new jobs for Anacron. The configuration file will look like this:

# /etc/anacrontab: configuration file for anacron

 

# See anacron(8) and anacrontab(5) for details.

 

SHELL=/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

HOME=/root

LOGNAME=root

 

#Start of job entries

#These replace cron’s entries

1   5     cron.daily      run-parts   --report    /etc/cron.daily

7   10   cron.weekly   run-parts   --report    /etc/cron.weekly

@monthly   15   cron.monthly   run-parts  --report    /etc/cron.monthly

 

    You can add entries to the configuration file in this format:

# period-in-days   delay-in-minutes   job-dentifier   shell-command

 

    Let’s look at this example.

30    15    data-backup1    /bin/bash /home/user/myscripts/data-backup.sh

 

    With this example, Anacron will run the data-backup.sh after the 30 days of inactivity, and it will have a delay of 15 minutes before executing the command. Then, the log file for this Anacron job will get stored as data-backup1.

    Compared to Cron, Anacron is not an automation program that will run scripts at the specified time. However, it will run scripts at a certain interval you have specified. To change the interval for the Anacron to execute the script, you can use the START_HOURS_RANGE command, which you need to put before the job entries. For example:

START_HOURS_RANGE=4-23


    With this interval example, Anacron will execute the jobs between the period of 4AM to 11PM.

You can also add another variable to set up an interval for Anacron, such as RANDOM_DELAY. This will set the maximum random delay you have specified, which is 15 by default.

    There are some shortcuts you can use for Anacron command lines, and Anacron uses the same shortcuts as Cron. So, for the earlier example, you can write the command line in this way:

@monthly   15    data-backup1    /bin/bash  /home/user/myscripts/data-backup.sh

 

Automated Options for Anacron

    With Anacron, there are various automated options you can use, which can simplify the task execution process for this software. You can do it by installing your scripts at specific directories, which Anacron will execute according to the specified schedule for each directory. It will go like these:

      /etc/cron.hourly – you can use this directory to run the scripts once each hour.

      /etc/cron.daily – use this directory to run Anacron scripts once daily.

      /etc/cron.weekly – you can use this directory to run the scripts once per week.

      /etc/cron.monthly – this is the directory to run the Anacron scripts once per month.

 

Conclusion

    Congratulations! With this guide, you have learned about how Cron works, how you can schedule tasks with Cron, and how you can use Anacron to run skipped cron jobs.

 

 


Do you have any suggestions for this document?

Your rating for this document: