Jan 6, 2013

Schedule tasks in Linux using cron

Cron is used to schedule tasks in Linux/Unix systems. It needs to runs as a daemon on the system. In most systems crond (cron daemon) is available and configured to run at the startup by default. You can check it by using;

ps -ef  | grep cron

If it is not running at the startup, start the daemon

service crond start

and set it to start at the system startup.

chkconfig crond on

Then you can do scheduling. If you view the '/etc/crontab' file you can get all the information needed to provide to automate an execution of a command.

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

# 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

You can run these commands as ether root or a normal user. Type 'crontab -e' to add/edit crons. If you type 'crontab -e' as a normal user, it will open a user specific cron list. If you need to schedule a task which require admin privileges, you need to login as root and type the 'crontab -e'.

Do a task in every 15 min.

*/15 * * * * root /usr/bin/command

or

0,15,30,45 * * * *  root /usr/bin/command

There are some more keywords you can when scheduling tasks. Those are;

@reboot
@yearly or @annually
@monthly
@weekly
@daily or @midnight
@hourly

You can use it like this;

@reboot  /root/scripts/mystartup.sh

You can modify a command to log the output of the execution to a specific file by;

@reboot  /root/scripts/mystartup.sh  >>/var/log/mystartupcron.log 2>&1

Note: Try to use absolute paths when editing commands in crontab.

No comments:

Post a Comment

Your comments are always welcome ...