How to Run a cron Job Every Two Weeks / Months / Days

By Zhiqiang Ma On Mar 25, 2013

Update: crontab provides some extensions to support this directly–’Ranges can include “steps”, so “1-9/2″ is the same as “1,3,5,7,9″‘. Check the crontab man page for more details. This post provides a “poor man”‘s solution to this problem.


We may want to run some jobs for every two weeks/months/days… under some situation such as bakup for every other week. In addition, we may add more complex rules for running jobs, e.g. run a command when the load of the server is higher than a certain level. With the help of the shell programming language we can easily achieve this goal.

The crontab line has this kind of format:

.---------------- minute (0-59)
|  .------------- hour (0-23)
|  |  .---------- day of month (1-31)
|  |  |  .------- month (1-12) OR jan,feb,mar,apr ...
|  |  |  |  .---- day of week (0-6) (Sunday=0 or 7) OR sun,mon,tue ...
|  |  |  |  |
*  *  *  *  *  command to be executed
The shell code:

#!/bin/bash
mark_file=/tmp/job-run-marker
# check whether the job runned last week
if [ -e $mark_file ] ; then
    rm -f $mark_file
else
    touch $mark_file
    exit 0
fi

# job command is here

The script will not find $markfile on the first run, so it will create it and exit. On the second run the script will remove $markfile and then proceed to execute the job command. For the third run, it is the same as the first run. So if this script is run weekly by cron, the job command will run every two weeks.

An example. We want to bakup xen DomU files for every two weeks. We create a script /lhome/share/bin/xen-bak. The start of this script is like what we list above. Then run

crontab -e
And add this line:
0 2 * * 2 /home/share/bin/xen-bak
The bakup command will run at 2:00 for every other Tuesday.

By: Zhiqiang Ma Last updated: Mar 25, 2013 Views: 7,899
Tags: , , , ,

About Zhiqiang Ma

Zhiqiang Ma is a PhD candidate at Dep. of CSE, HKUST. He is interested in system software for cloud computing, virtualization of large-scale distributed system, etc. Find Zhiqiang on Facebook, Twitter, LinkedIn and Google+.

3 Comments on How to Run a cron Job Every Two Weeks / Months / Days | Add Comment
Add your comments, share your thoughts

Be nice. Keep it clean. Stay on topic. No spam.