Let’s first see what does cron
represent from wiki:
The software utility
cron
is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments usecron
to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.
cron
is most suitable for scheduling repetitive tasks. For example, it runs log file rotation utilities to ensure that your hard drive doesn’t fill up with old log files. You should know how to use cron because it’s just plain useful.
Also see cronjob in K8s.
Install crontab
In CentOS or RedHat, you can run:
1 | yum install cronie |
If you are not sure, try yum provides crontab
to see which package will provide this service.
To check if cron
service is running or not:
1 | systemctl status crond |
If inactive, enable and restart it.
crontab File
Cron is driven by a crontab(cron table)
file, a configuration file that specifies shell commands to run periodically on a given schedule.
The program running through cron is called a cron job
. To install a cron job
, you’ll create an entry line in your crontab
file, usually by running the crontab
command.
Each user can have his or her own crontab file, which means that every system may have multiple crontabs, usually found in /var/spool/cron/
folder. the crontab command installs, lists, edits, and removes a user’s crontab.
crontab Commands
For example, run as root
, I want to set a recurring task for user dsadm
:
1 | crontab -u dsadm -e |
Then edit like this:
1 | 00 21 * * * /home/dsadm/test.sh > /tmp/cron-log 2>&1 |
This means on everyday at 9:00PM, user dsadm
will run test.sh
and redirect output to /tmp/cron-log
file. You can also put the entries into a file and run:
1 | crontab -u dsadm <entry file> |
The meaning of the entry is:
1 | # ┌───────────── minute (0 - 59) |
A
*
in any field means to match every value.
Now, if you check /var/spool/cron
directory, the dsadm
crontab file is created there.
To list the dsadm
cron job:
1 | crontab -u dsadm -l |
To remove dsadm
cron job:
1 | crontab -u dsadm -r |
Run as Non-Root
If you want to run crontab
as dsadm
, you must set the cron permission:
/etc/cron.allow
- If this file exists, it must contain your username for you to use cron jobs./etc/cron.deny
- If the cron.allow file does not exist but the/etc/cron.deny
file does exist then, to use cron jobs, you must not be listed in the/etc/cron.deny
file.
So, if you put dsadm
in /etc/cron.allow
file, then you can use crontab
directly.
System crontab File
Linux distributions normally have an /etc/crontab
file. You can also edit here, but the format is a little bit difference:
1 | # Example of job definition: |