tips

Introduction

From: Wikipedia

Cron is a time-based job scheduler in Unix-like computer operating systems. The name cron comes from the word “chronos”, Greek for “time”.[1] Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email

Cron is driven by a crontab (cron table) file, a configuration file that specifies shell commands to run periodically on a given schedule. The crontab files are stored where the lists of jobs and other instructions to the cron daemon are kept. Users can have their own individual crontab files and often there is a system wide crontab file (usually in /etc or a subdirectory of /etc) which only system administrators can edit.

So, as you can see, cron is really useful to perform repetitive tasks in a Linux machine, or to run some specific task in a given hour and day only one time.

In other words is a scheduler of jobs for Linux

Editing Crontab

Log in as the user you want to edit his / her crontab and run:

crontab -e

To list his cronjobs

crontab -l

If you have access to root account you may edit anyone’s files.

crontab -u [user] -e

Changing the default Linux editor program

By default the editor for crontab is vi, but you can change it, just run:

export EDITOR=/usr/bin/nano

Now, if you run

crontab -e

you will be editing the file using nano

Tips and example for Crontab

Syntax

MIN HOUR DOM MON DOW CMD

Where

  • MIN = Minute 0-59
  • HOUR = Hour 0-23
  • DOM = Day of month 1-31
  • MON = Month 1-12
  • DOW = Day of week 0-6 Where 0=Sunday
  • CMD = Command, the command that is going to run in a given moment.

You may want to check also the differences in crontab syntax depending the version you are using or the Linux distribution you are working with.

Schedule a task for an specific moment one time run

12 02 2 11 * /home/user/my-task.pl

So, at 2:12 am on November the 2nd the program /home/user/my-task.pl will run.

Run a command twice in a day, month, or any other time frame

You can use commas to tell the Operating System you want to run the program twice. Let’s suppose in the above example, you want to run on November and December the same program.

12 02 02 11,12 * /home/user/my-task.pl

Run a command in time intervals, like weekdays

00 14 * * 1-5 /home/user/my-task.pl

What about only on weekends and in the morning

06-12 * * 6,7 /home/user/my-task.pl

Run once every year, month, day

You can use these special words for this:

  • @yearly -Every year January first 00:00
  • @daily -Every day at 00:00
  • @hourly -Every hour at 0 minutes
  • @reboot -As soon as you reboot your computer

Run a program every X minutes

Let’s say you want to run a command every 15 minutes, enter this line the crontab file:

*/15 * * * * command