Scheduling Tasks with Cron


Just like in Windows, Linux offers the possibility of running scheduled tasks within a specified period of time or date. There are several tools that can be used to configure recurring tasks and one of the most common is cron. This is an inbuilt feature with CentOS distributions and can be easily configured to run certain tasks based on several criteria: minute, hour, day of month, month, day of week. Make sure that crond (cron daemon) is installed and running before trying to schedule or execute tasks. To verify if the service is running, execute one of the following commands:
service status crond
/etc/init.d/crond status
Linux cron
A task configured in cron it’s called a cronjob. These jobs are configured in the crontab file that can be found in  cat /etc/crontab:
Scheduling Tasks with Cron
Crontab fields can take one of the following values:

minute – a number from 0 to 59
hour – number from 0 to 23
day – a number from 1 to 31 but make sure the month has the specified date!

month – number from 1 to 12
day of week – a number from 0 to 7.
user-name – username that will be used to run the specified cronjob
command – what command/script to be executed during the job
The * specifies all values within a field
– (hyphens) can be used to specify a range. For example, 1-4 in the day of week field specifies the interval in which the job will run
, (comma) can be used to specify several values.

A System can have one crontab file for each user. To add a crontab file for a specific user use the crontab file command. crontab -l can be used to list cron jobs and crontab -r to remove a crontab file.
All user-defined crontabs are stored in the /var/spool/cron/ directory and are executed using the usernames of the users that created them from here

/etc/cron.allow and /etc/cron.deny files are used to specify what users has access to cron. You have to enter one username per line.

The following lines are some examples of crontab entries:
* * * * * /usr/bin/php /var/www/html/site1/a.php – every minute every day
0 9 1-20 1-6 * /usr/bin/php /var/www/html/site1/a.php – at 09:00 from the 1st to 20th from January to June
15 9 1-5 1-2 * /usr/bin/php /var/www/html/site1/a.php – at 09:15 from the 1st to 5th from January to February
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s