1837932 Members
2624 Online
110124 Solutions
New Discussion

setup the crontab job

 
SOLVED
Go to solution
hangyu
Regular Advisor

setup the crontab job

If I would like to set a crontab schedule job that run one time only per month , the day must the first Sunday of every month , I try " 0 1 1 * 0" , but it will run every Sundy and 1st , can advise what can I set ? thx
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: setup the crontab job

Cron by itself cannot do this and although you thought that by specifying both a weekday and a monthday, you were specfying a logical AND as you have discovered it is a logical OR. What you can do is have cron run the job every Sunday and then let the job itself determine if this is the 1st Sunday or if not simply exit. Use the attached script, caljd.sh, to determine if it is the 1st occurence of a given weekday in the month. I would install it in /usr/local/bin.

Your cron'ed script should look something like this:
--------------------------------
#!/usr/bin/sh

export PATH=${PATH}:/usr/local/bin

if [[ $(caljd.sh -N) -eq 1 ]]
then
echo "It's the first Sunday; do your thing"
else
# it's not
exit 0
fi
If it ain't broke, I can fix that.
Bill Hassell
Honored Contributor

Re: setup the crontab job

Can't be done with cron. Each item in the list (min hr day month wkday) is checked and a match for any setting will trigger the job. TTo accomplish what you want, you need to write your cron script to see if the current day of the month is 1-7, and if not true, exit. Then add the job to cron to run every Sunday. The script will choose the first week of the month.


Bill Hassell, sysadmin
A. Clay Stephenson
Acclaimed Contributor

Re: setup the crontab job

Oops, I'm an idiot. I forgot to attach the caljd.sh script. Here it is. Invoke as caljd.sh -u for full usage and many examples as it makes otherwise difficult date calculations trivially simple.

If it ain't broke, I can fix that.
Dennis Handly
Acclaimed Contributor

Re: setup the crontab job

If you want to just check for Sunday, instead of using Clay's script, you can do:
DAY=$(date +%a)

If you are worked about locales, you can use:
DAYOFWEEK=$(date +%u)

Where Sunday is 7.
if [ $DAYOFWEEK -eq 7 ]; then # Sunday