Tuesday, December 28, 2010

Executing cronjobs on specific days in a month

You can use this post as a reference to schedule the Cronjobs in more Granular fashion.

Situation:
We had a requirement to execute couple of scripts on specific Saturdays of a month throughout the year  i.e., First script (say /opt/firstscript.sh) should be executed on all Saturdays EXCEPT first Saturday of the month, and the Second script (say /opt/secondscript.sh) should be executed ONLY on first Saturday of the month. This we required to do for scheduling Weekly Tape backups.

Executing a script on all Saturdays is fairly simple, we need to just specify number 6 on 5th column on crontab entry, but here the scenario is different.
The solution for this is shown below. This uses ‘date’ command to check if the current date is a first Saturday of a month.

0  2  *  *  6     [ $(date +%d) -gt 7 ]  && /opt/firstscript.sh               
# Executes at 2am on all Saturdays Except the first Saturday of the month (Saturdays other than 1st  can fall only after 7th ).

0  22  *  *  6   [ $(date +%d) -le 7 ]  && /opt/secondscript.sh        
# Executed at 10 PM ONLY on first Saturday of the month (A first Saturday can either be 7th or less than that ).

5 comments:

  1. wouldn't

    0 2 8-31 * 6 /opt/firstscript.sh

    and

    0 22 1-7 * 6 /opt/secondscript.sh

    work as well?

    ReplyDelete
  2. Hi Dennis,

    The solution what I mentioned in this post is the right one. We have been using this logic in our production to schedule weekly Backup jobs i.e. everyday 1st saturday of the month, we got to trigger Offsite backup and rest of the saturdays, we got to trigger weekly backups.

    The cron entry what you provided wouldn't work. Reason: In Crontab, the Date fields, and the Day of week fields, are OR'd together, so it would run secondscript.sh every day the first week, and every Saturday.

    Thanks for your inputs.

    Ashok

    ReplyDelete
  3. Dear Ashok ,
    My name is Rahul Kumar. I read ur Blog.I like it very much .I learn few new things from your blog.

    I want to ask one question from you .

    I want to schedule Cronjob which must run everday and repeat every 5 mins in all week days .eg. i want to run ls -ltrh command via crontab.

    plz tell me your e-mail address also .


    Regards,
    Rahul Kumar

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. @Rahul, Below given command will work!

    */5 * * * * ls -lrth /home/user

    ReplyDelete