Scheduling tasks on Linux machine(CentOS)

Sometimes you need to run certain tasks on certain time. You can configure tasks to run in future. Cron helps you to run jobs scheduled times.  Cron daemons look every minute whether there is a job to do.

By default cron service started by default. because some systems tasks are running through cron like logrotate, a service cleans logs and runs on a regular basis.

Check whether cron is running on your machine

UNDERSTAND CRON TIMINGS

When you are going to schedule tasks, you need to specify when exactly the services need to be started.

Field Value
minute 0 – 59
hour 0 – 23
day of month 1 – 31
month 1 – 12
day of week 0 – 7 (Sunday is 0 or 7)

You can use * to refer to any value.

Some examples are –

* 11 * * *  (between 11:00 to 11:59)

0 11 * * 1-5  (Everyday at 11 a.m. on weekdays)

0 7-18 * * 1-5  (Every hour on weekdays)

0 */2 2 12 5  (Every 2 hours on december 2 and every friday)

The main configuration file of cron is /etc/crontab

instead of modfying crontab, different files are used –

  • cron files in /etc/cron.d
  • Scripts in /etc/cron.hourly, cron.daily, cron.weekly, cron.monthly
  • User specific files that are create with crontab -e

start job for specific user using crontab -e or start for the specific user using root crontab -e  -u >user>

After executing above command open editor and creates a temporary file. After this, it will be moved to its file location in the directory /var/spool/cron

This script will launch every minute.

Another way is to schedule cron jobs through the following directories

  • /etc/cron.hourly
  • /etc/cron.daily
  • /etc/cron.weekly
  • /etc/cron.monthly

You can put your scripts in these directories. There is no information about the timings because exact time of executing doesn’t matter. The only thing doest matter is launched once a hour, daily, weekly and monthly.

UNDERSTAND ANACRON

To ensure the execution of the job, the cron used anacron service. This service takes care of run jobs at hourly, daily, weekly and monthly basis, no matter at what time.

CRON SECURITY

By default, all users can enter cron jobs. if /etc/cron.allow file exists then allowed user should in the file. If the /etc.cron.deny file exists, then the user must not be listed in the file.

you can list own jobs using crontab -l

show jobs of other users using root

CRON SPECIAL KEYWORDS

Keyword Decription
@yearly  0 0 1 1 *
@daily  0 0 * * *
@hourly 0 * * * *
@reboot Run at startup

REMOVE CRON JOBS

 

SOME OTHER CRON JOB EXAMPLES

*/5 * * * * /home/amit/backup.sh – Every 5 minute

0 */5 * * * /home/amit/backup.sh – Every 5 hour

You can not execute jobs in seconds.

 

 

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">