Schedule tasks with Linux crontab

Sometimes you need process that running continuously, every day, every hour, every month or whatever. With this article, i’ll show you how to using of crontab, very simple and easy to use. you can using crontab for synchronize file, update your application, send email, etc. Crontab is linux time based scheduler, user can put the scheduler even its shell scripts or command to run periodically in background. If you want to see what kind of scheduler that regulated, open your terminal and run :


$ sudo crontab -l

How about if you want to add schedule in crontab? simple, just run :


$ sudo crontab -e

In default, crontab come with 5 asterisk sign (*), some people called it “star”. like this :

*    *    *    *    *  sh /home/user/nameOfFile.sh
┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week (0 - 7) (0 or 7, are Sunday, Monday and so on)
│    │    │    └────────── month (1 - 12)
│    │    └─────────────── day (1 - 31)
│    └──────────────────── hour (0 - 23, remember we use 24 hours, not 12 hours)
└───────────────────────── min (0 - 59)

In above command, we have 5 asterisk, which means that script will running periodically every 1 minutes. Remember for day of week :

  • 0=Sun
  • 1=Mon
  • 2=Tue
  • 3=Wed
  • 4=Thu
  • 5=Fri
  • 6=Sat

Execute everyday at 1 AM

0    1    *    *    *  sh /home/user/nameOfFile.sh

Explanation :

  • Minutes = 0
  • Hour = 1 AM
  • Day of Month = Every Day of Month
  • Month = Every Month
  • Day of Week = Every Day of Week

Execute in day 1 and 15 in month at 1 AM.


0    1    1,15    *    *  sh /home/user/nameOfFile.sh

Explanation :

  • Minutes = 0
  • Hour = 1 AM
  • Day of Month = 1, 15 means day 1 and day 15 in month.
  • Month = Every Month
  • Day of Week = Every Day of Week

Execute every work day (Monday – Friday) at 8 AM.


0    8    *    *    1-5  sh /home/user/nameOfFile.sh

Explanation :

  • Minutes = 0
  • Hour = 8 AM
  • Day of Month = Every Day of Month.
  • Month = Every Month
  • Day of Week = 1-5 means from Monday to Friday, or you can use Mon-Fri. It will give us same result.

Crontab can send you an email too, just run crontab -e, and add MAILTO, like this :


MAILTO = 'my.email@gmail.com'
*   *    *    *    *  sh /home/user/nameOfFile.sh

If you add mail name like above, crontab will send you an email every execute job. but remember you have to setting email client in your linux like sSMTP. in this case, if you have many schedule and you dont want the unimportant job spam your email, simply you can do like this :

*   *    *    *    *  sh /home/user/nameOfFile.sh >/dev/null 2>&1

when you running a crontab, You can look a log file in /var/log/syslog. I prefer use “tail” when looking at it. 🙂

Regards,

tandatangankecil

Leave a Reply

Your email address will not be published. Required fields are marked *