The Computer Oracle

Run a cron job on the first Monday of every month?

-------------------------------------------------------------------------------
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
-------------------------------------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
00:49 Accepted answer (Score 57)
01:52 Answer 2 (Score 28)
02:16 Answer 3 (Score 11)
03:00 Answer 4 (Score 7)
03:28 Thank you

--

Full question
https://superuser.com/questions/428807/r...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#cron #crontab

#avk47



ACCEPTED ANSWER

Score 59


You can put the condition into the actual crontab command (generic way):

[ "$(date '+%u')" = "1" ] && echo "It's Monday"

if your locale is EN/US, you can also compare strings (initial answer):

[ "$(date '+%a')" = "Mon" ] && echo "It's Monday"

Now, if this condition is true on one of the first seven days in a month, you have its first Monday. Note that in the crontab, the percent-syntax needs to be escaped though (generic way):

0   12  1-7 *   *   [ "$(date '+\%u')" = "1" ] && echo "It's Monday"

if your locale is EN/US, you can also compare strings (initial answer):

0   12  1-7 *   *   [ "$(date '+\%a')" = "Mon" ] && echo "It's Monday"

Replace the echo command with the actual command you want to run. I found a similar approach too.




ANSWER 2

Score 29


I have a computer with locale on Spanish, so, this approach isn't working for me because mon changes to lun

Other languages would fail as well, so, I did a slight variation on the accepted answer that takes out the language barrier:

 0 9 1-7 * *   [ "$(date '+\%u')" = "1" ] && echo "¡Es lunes!"



ANSWER 3

Score 11


I find it easier when there's no need to handle day numbers.

Run First Monday of month:

0 2 * * 1 [ `date '+\%m'` == `date '+\%m' -d "1 week ago"` ] || /path/to/command

i.e. if the month 1 week ago is not the same as the current month then we are on the 1st day 1 (= Monday) of the month.

Similarly, for the Third Friday

0 2 * * 6 [ `date '+\%m'` == `date '+\%m' -d "3 weeks ago"` ] || /path/to/command

i.e. if the month 3 weeks ago is different to current month then we are on the 3rd day 6 (= Friday) of the month




ANSWER 4

Score 7


Since I interpret my cron statements using PHP and JavaScript, I can't use bash. Finally I found that it is in fact possible with just cron:

0 30 8 * 1/1 MON#1