Home » Linux

How to run a cron job every two weeks/months/days

By: Zhiqiang Ma On: Feb 20, 2010 Views: 169 Comments: 2 Print Email
Tags: , , , , ,

cron can only run the job for every one week/month/day/…. 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,wed,thu,fri,sat
|  |  |  |  |
*  *  *  *  *  command to be executed

But we may want to run some jobs for every two weeks/months/days… under some situation such as bakup for every other week. With the help of the shell programming language we can easily achieve it:

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 $mark_file on the first run, so it will create it and exit. On the second run the script will remove $mark_file 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

crontabs -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.

Read more:

Digg del.icio.us Stumble Techorati Facebook Newsvine Reddit Twitter
Mixx LinkedIn Google Bookmark Yahoo Bookmark MySpace LiveJournal Blogger RSS feed
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

2 Comments »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

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

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.