In recent past i use to do certain tasks at some scheduled time on the day which also included shutting down one of my machine at 8 PM. Then I came to know that this could be effectively done automatically using cron and so I am discussing cron in this post.
Cron is a daemon which schedules recurring tasks to be executed at a predefined time and date . It is very easy to schedule a job to be run at a particular time using cron. Cron daemon is typically started at boot time and runs continuously in the background. Cron maintains a table of tasks in a file named crontab which is usually in /etc directory. Each user can have separate cron file In order to access the current cron table, the crontab command is used as follows :
The above command will load the user's crontab in an editor - usually 'vi '- for editing by the user.
The crontab file contains 6 fields which are as follows :
Min Hours day-of-month month day-of-week command-to-run
And the values of these fields can take the following form:
Min - 0-59
Hours - 0-23
day of month - 1-31
month - 1-12 or Jan-Dec
day of week - 0-7 or Sun-Sat
Fields in a crontab
may be separated by any number of tabs
. And a '*
' symbol in a field represent all valid values.
Suppose I am logged in as root and want to modify a crontab file of a particular user. Then I use the '-u' switch
crontab -u username -e
And to list the crontab,
You can remove the crontab using the -r switch:
Restrict or allow user access to cron
Using the two files, /etc/cron.allow and /etc/cron.deny, root can allow or restrict a user from using cron.
System crontab files
- Master crontab file
- directory containing additional system crontab files.
The syntax of the system crontab file is slightly different from the user crontab file explained above. In the system crontab file, the sixth field is a username which will be used to execute the command in the seventh field.
Below is the listing of my system crontab file - /etc/crontab
# File: /etc/crontab
01 * * * * root run-parts /etc/cron.hourly
00 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
As seen above, run-parts is a shell script which takes one argument, a directory name, and invokes all of the programs in that directory. The directories cron.hourly, cron.daily, cron.weekly and cron.monthly contain executables which are run by the master crontab file /etc/crontab . Thus at 4:00 every morning, all of the executables in the /etc/cron.daily directory will be run as root.
If you view the /etc/cron.daily directory, you can see a lot of executables which are run daily at a predefined time as specified in the /etc/crontab file.
In my case I added the following lines
00 20 * * * root /sbin/halt (To shut down system @ 8 PM daily)
00 13 * * 0 root /sbin/halt
(To shut down system @ 1 PM on sundays)
using this I was able to automatically shutdown machines once the clocked said its time to close.