1758586 Members
1899 Online
108872 Solutions
New Discussion юеВ

Plannig cron job

 
SOLVED
Go to solution
Igor Sovin
Super Advisor

Plannig cron job

Hi!
I'm wondering how to plan cron job that runs every forth monday at 4.00 of every month?
4 REPLIES 4
RAC_1
Honored Contributor
Solution

Re: Plannig cron job

You can not do it directly in cron. you need to use a script that will run on every monday and will execute it further, if it is a 4th monday on the month.
There is no substitute to HARDWORK
A. Clay Stephenson
Acclaimed Contributor

Re: Plannig cron job

Cron by itself is not smart enough to do this but coupled with a small utility it can do the job. The trick is to run a script every Monday and then let the script decide if it should execute something or simply exit.

1) Download the attached script, caljd.sh and install it in /usr/local/bin. Set the mode of this file to 755; chmod 755 /usr/local/bin/caljd.sh

2) Create a wrapper script that calls this utility. e.g. /usr/local/bin/mycrontask.sh

---------------------------
#!/usr/bin/sh

PATH=${PATH}:/usr/bin:/usr/local/bin
export PATH
STAT=0
if [[ $(caljd.sh -N) -eq 4 ]]
then
echo "Do your stuff here; it's the 4th Monday"
# remember to set ${STAT} to a non-zero value on failure
fi
# otherwise simply exit
exit ${STAT}
--------------------------------------

3) crontab -l > mycrontab
edit mycrontab and add this line
0 4 * * 1 /usr/local/bin/mycrontask.sh
save the file and
crontab < mycrontab


Here's the caljd.sh attachment. Invoke it as caljd.sh -u for full usage and many examples.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Plannig cron job

I assume that by 4:00 you meant 4:00 AM if not change the '4' crontab entry to '16'.
If it ain't broke, I can fix that.
Muthukumar_5
Honored Contributor

Re: Plannig cron job

You can not directly do with crontab settings.

Work around is,

i) Use crontab setting as:

0 4 * * 1 <script to be executed as /test.sh> 1>/dev/null 2>&1

==> Execute at 4:00 on monday (1). It will execute on all weeks.

ii) To control to execute on month's forth monday then,

<script to be executed as /test.sh>
#!/bin/sh

if [[ $(date +'%d') = $(cal | grep -v '[a-z]' | cut -b 4-5 | grep -Ev ' |^$' | head -4 | tail -1) ]]
then

fi

# END
exit 0

PS:
You got a solution from olympian. This is with system default utility using cal instead of external script.

hth.
Easy to suggest when don't know about the problem!