How to use CRON in Linux

how-to-use-cron-in-linux
Getting your Trinity Audio player ready...

How to use CRON in Linux

CRON is a standard utility available in all unix like operating systems including linux which is used for automation of repetitive tasks like housekeeping stuff without any investment. In this article, we are going to discuss how to use cron in linux

What is CRON?

CRON full form or acronym is Command Runs ON – UNIX Scheduler. CRON is one of the most important tools which is helpful to schedule jobs. Most probably the routine frequent jobs. CRON is part of all the UNIX-based operating systems including linux. 

CRON runs on a local server and it does not have any agent running. All CRON instance runs as a single process on the server so each instance of CRON is separate and problem in one instance does not impact others. In CRON there is no Single Point of Failure.

Each user of the server can run their own CRON to maintain or automate stuff on the server. There will be maintenance overhead if you want to make changes on all nodes in bigger organizations you have to update all the servers in the environment. There are alternatives to CRON for the enterprise sector like Control-M.

How CRON Works on Linux?

crond is a daemon that executes commands as defined by user./etc/sysconfig/crond contains settings for cron daemon. Normally you need not touch this file.

#ls -l /etc/sysconfig/crond
-rw------- 1 root root 110 Feb 13  2019 /etc/sysconfig/crond
# cat /etc/sysconfig/crond
# Settings for the CRON daemon.
# CRONDARGS=:any extra command-line startup arguments for crond
CRONDARGS=

Normally crond daemons check every minute if any job needs to be run. These are user-based configurations and each user can run their own cron including run by system administrators using root.

All cron jobs known as crontab and all crontab files stored in /var/spool/cron for all users.

Cron files are stored under /etc with different structures like cron.d, cron.daily, cron.hourly, cron.monthly, cron.weekly.These are master control files as the name specified.

Cron Log Files in Linux

the Syslog daemon is central log management for a local server. syslog.conf is the central location log configuration file for the linux server. It logs all notable events. Log location for CRON is defined in it which shows the path where CRON logs are saved. Normally it is /var/log/cron.

# cat /etc/syslog.conf |egrep "cron"
*.info;mail.none;authpriv.none;cron.none  /var/log/messages
# Log cron stuff
cron.*                                                  /var/log/cron
You can see cronlogs using
# cat /var/log/cron
You can monitor cron logs using
#tail -f /var/log/cron

Crontab Syntax in Linux

To run jobs automatically at regular intervals cron service can be used. You can schedule repeating jobs using the crontab command. It is important to understand.

Below is an example of a job that executes every day at 1:05 AM.

05 01 * * *  validate.sh

You can understand syntax using the below output.

# cat /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

Let’s see the man page for crontab to make it more clear.

# man crontab
crontab - maintains crontab files for individual users
SYNOPSIS
crontab [-u user] file
crontab [-u user] [-l | -r | -e] [-i] [-s]
crontab -n [ hostname ]
crontab -c
DESCRIPTION
Crontab  is  the program used to install a crontab table file,remove or list the 
existing tables used to serve the cron daemon.  Each user can have their own 
crontab, and though these are files in /var/spool/, they are not intended to 
be edited directly.  
For SELinux in MLS mode, you  can define more crontabs for each range. 
In  this version of Cron it is possible to use a network-mounte d shared /var/
spool/cron across a cluster of hosts and specify that only one of the hosts 
should run the crontab jobs in the particular directory at any one time.  You 
may also use crontab from any of these hosts  to  edit  the same shared set of 
crontab files, and to set and query which host should run the crontab jobs.
OPTIONS
-l     Displays the current crontab on standard output.
-r     Removes the current crontab.
-e     Edits the current crontab using the editor specified by the VISUAL or ED
ITOR environment variables.  After you exit from  the  editor,  the modified 
crontab will be installed automatically.
-i     This option modifies the -r option to prompt the user for a 'y/Y' response
before actually removing the crontab.
-s     Appends  the  current SELinux security context string as an MLS_LEVEL
setting to the crontab file before editing / replacement occurs – see the docum
entation of MLS_LEVEL in crontab.
-n     This option is relevant only if cron was started with the -c option, to ena
ble clustering support.  It is used to set the  host  in  the cluster  which  should
run  the jobs specified in the crontab files in the /var/spool/cron directory.  
If a hostname is supplied, the host whose hostname returned by gethostname
matches the supplied hostname, will be selected to run the selected cron jobs
subsequently.   If there  is  no  host in the cluster matching the supplied hostn
ame, or you explicitly specify an empty hostname, then the selected jobs will 
not be run at all.  If the hostname is omitted, the name of the local host return
ed by gethostname is used.  Using this  option  has  no effect  on  the /etc/cro
ntab file and the files in the /etc/cron.d directory, which are always run, and
considered host-specific. 
 -c     This option is only relevant if cron was started with the -c option, to ena
ble clustering support.  It is used to query  which  host  in the cluster is curren
tly set to run the jobs specified in the crontab files in the directory /var/spool
/cron , as set using the -n option.

How to Allow or Deny crontab access using /etc/cron. allow and /etc/cron.deny?

You can control crontab access who can run cronjobs on the system using cron.allow and cron.deny files. If cron.allow file exists in server user must be part of file means it is allowed.

If the cron.allow file does not exist in the server but the cron.deny file does exist in that case user must not be listed in the cron.deny file in order to use cron. 

If cron.allow and cron.deny both files does not exist in server in that case only the superuser is allowed to use cron. This is the default behavior of the system.

Another method how you can restrict access to cron is via using PAM authentication in /etc/security/access.conf to set up users, which are allowed or disallowed to use crontab or modify system cron jobs in the /etc/cron.d/ directory.

Understand default behavior of linux server.

# ls -l /etc/cron.allow
ls: cannot access /etc/cron.allow: No such file or directory
# ls -l /etc/cron.deny
-rw------- 1 root root 0 Feb 13  2019 /etc/cron.deny

In the above example cron.allow does not exist but cron.deny exists but of zero-byte means no entry of denying statement. In this scenario, only a superuser is allowed for cron.

How to Display, List, View All Cron Jobs in Linux for himself?

To get all the cron jobs for a user you can use the crontab -l command as a user. Below is the sample output as the root user.

# crontab -l
* * * * * [ \( ! -f /etc/opt/omi/creds/omi.keytab \) -o \( /etc/krb5.keytab
 -nt /etc/opt/omi/creds/omi.keytab \) ] && /opt/omi/bin/support/ktstrip 
/etc/krb5.keytab /etc/opt/omi/creds/omi.keytab

How to Display, List, View All Cron Jobs in Linux for any other users?

Below is an example of how you can check other user’s cron jobs. For this, you need to have elevated privileges or root access.

# crontab -u monitorsvc -l
#__BEGIN__COLLECTD5 Note: any edits of lines between BEGIN__
COLLECTD5 and END__COLLECTD5 will be lost
0,5,10,15,20,25,30,35,40,45,50,55 * * * * ps -eo comm | grep collectdmon >/dev
/null || /export/home/monitorsvc/collectd5/sbin/collectdmon -c /export
/home/monitorsvc/collectd5/sbin/collectd
0 * * * * PATH=/export/home/monitorsvc/bin:/export/opt/perl/bin:$PA
TH /export/home/monitorsvc/sbin/slack --sleep 1800 collectd5-conf.`/expo
rt/home/monitorsvc/bin/urole`.`uname -n`
2 17 * * 5 mv -f /export/home/monitorsvc/collectd5/var/log/collectd.log 
/export/home/monitorsvc/collectd5/var/log/collectd.log.lastweek
#__END__COLLECTD5

How to Check Cron Service Status in Linux?

Below is the command to check cron service status in RHEL6.
# service crond status
crond (pid  2995) is running...
Below is the command to check cron service status in RHEL7.
# systemctl status crond.service
â crond.service - Command Scheduler
Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor 
preset: enabled)
Active: active (running) since Tue 2021-04-27 19:55:44 EDT; 3 weeks 0 days 
ago
 Main PID: 2657 (crond)
CGroup: /system.slice/crond.service
2657 /usr/sbin/crond -n

How to Manage Cron Services in Linux?

Below the set of commands, you can manage cron services in RHEL6. All commands are self-explanatory of what action it is going to perform.

# service crond stop
# service crond start
# service crond restart
# service crond reload

Below the set of commands, you can manage cron services in RHEL7. All commands are self-explanatory of what action it is going to perform.

# systemctl stop crond.service
# systemctl start crond. service
# systemctl reload crond.service
# systemctl restart crond.service

How to Setup a Cron Job in Linux?

As described above about the syntax of cron job let’s simplify it.

p q r s t  <command path>

Where p,q,r,s,t all is related to time and repetition related. Just to mention time format is considered as 24hrs.

Field  Values Syntax Description
[p] – Minute 0 – 59 5 * * * *  the cron job runs every time when the clock shows 5 in a minute.
[q] – Hour 0 – 23 0 5 * * * the cron job runs any time when the clock shows 5 AM.
[r] – Day 0 – 31 0 0 1 * *  Day of the month is 1 means job runs every Ist day of the month.
[s] – Month 0 = none and 12 = December 0 0 0 8 * If the month is 8 job runs only in Aug.
[t] – Day of the Week 0 = Sunday and 7 = Sunday 0 0 * * 7  7 means the job only runs on Sundays.

 

How to Add, Edit Cron Jobs in Linux?

As mentioned above all the cronjobs is related to the user base. So as a user you can use crontab -e to set up and edit cronjob for a specific user. Below are sample jobs for root user in one of the azure rhel7 virtual machine.

# crontab -e
* * * * * [ \( ! -f /etc/opt/omi/creds/omi.keytab \) -o \( /etc/
krb5.keytab -nt /etc/opt/omi/creds/omi.keytab \) ] && 
/opt/omi/bin/support/ktstrip /etc/krb5.keytab /etc/opt/
omi/creds/omi.keytab

Again if you are trying to create a cronjob for other users you need to have elevated access to the server or you need to be a superuser.

# crontab –u apache –e

It is almost the same as above. You can save files after edit and reload the crond service and you are done. Just remember if you are using any script inside cronjob it is already better to validate your script manually to make sure your script is working to get the best results. crontab -e invokes vi editors.

How to Remove Cron Jobs in Linux?

# crontab -r

It will remove all the cronjobs for a specific user. You can achieve the same by manually deleting the user’s file in /var/spool/cron and refresh the crond daemon.

Cron Job Examples

Let us see few cron job examples

50  16  1,15  1,3,6,8  /usr/backup.sh

This job will run at 4:50 PM on the First and Fifteen of Jan, March, June, and August. You can write the same as below as well quoting initials of Month as well.

50 16 1,15 Jan,Mar,Ju,Aug /usr/backup.sh

You can use this for housekeeping of servers like logrotate, log monitoring, and even as you wish and your familiarity with bash scripting. If you are good at shell scripting you can utilize it more efficiently to keep your system healthy and secure to deliver to business as expected.

Conclusion

You will now have a good idea about how to use cron in Linux. You can create a new cron job, edit cron jobs, remove cron jobs, check the cron service status, manage crond daemon status. You can use examples shared in the article as a tutorial. As mentioned above your expertise gets improved as you practice those and it will become efficient with bash scripting knowledge which is essential for all linux administrators.

Please share your valued suggestion if anything got missed in the article in form of comments if you like to see anything more about how to use cron in Linux. If you like our work please subscribe and share in your circle and allow this post reach to the intended audience.