2

Good day,

I need to run job in Jenkins monthly, two days before the end of the month.

The question is similar to question: run cron job on end of every month , but accepted response is not acceptable in my case. (Because modifying production code is out of scope and people would still like to execute it outside set hours.)

I found similar issues and potential solution in generic crontab environment:

0 23 27-30 * * [ $(date +\%d -d "2 days") == 01 ]

But Jenkins does not support this sort of syntax, giving me error message:

Invalid input: "0 23 27-30 * * [ $(date +\%d -d "2 days") == 01 ]": line 1:15: expecting EOF, found ' '

Any Jenkins gurus to give pointers?

Edit: With help of answer below, I came up with following solution:

  • Add string parameter Autorun
  • Set Crontab to H 4 26-30 * *
  • Modfied Execute script:

_

 if (($Autorun == 0)) || (( [ $(date +\%d -d "2 days") == 01 ] && $Autorun == 1  )); then 
   My_execute stuff
else
   echo "Dummy run, autorun only 2 days before end of month."
   exit 1
fi
pinegulf
  • 1,334
  • 13
  • 32

2 Answers2

3

It's not necessary to set up three jobs. One job can have multiple cron expressions in Jenkins: enter image description here The line on the bottom shows this should work as desired.

So you could use the following:

0 23 30 1,3,5,7,8,10,12 *
0 23 29 4,6,9,11 *
0 23 27-28 2 *

This still has the drawback for February that it runs twice in leap years, which is harder to avoid. If that's a problem, but it's not an issue to run one day early in leap years, you could just use 27 instead of 27-28.

Socci
  • 337
  • 2
  • 12
2

Unfortunately Jenkins Build triggers do not support writing bash script inside them. There are still options though, depending on how strict your requirement of "2 days before end of month" is.

Option 1:

Only run my job once per month:

@monthly

Option 2:

Run the job on second to last day of each month:

0 23 27-30 * *

Option 3:

Run it as 3 separate jobs as in this

This would then require you to add the date check at the start of the script portion of the job and exiting if it is not the second to last day of the month.

For more information you can "configure" a job and click on the blue question mark symbol which shows lots of information on how jenkins interprets that cron syntax.

Steve Robinson
  • 452
  • 5
  • 9
  • Option 2 sounds promising... I'm thinking of modifying execute script to `if (( [ $(date +\%d -d "2 days") == 01 ])); then DoStuff else echo "Dummy run, autorun only 2 days before end of month." exit 1 fi` – pinegulf Mar 15 '18 at 10:19
  • Yeah that sounds sensible - or if you are happy to have 3 jobs to manage then the 3rd option could work too – Steve Robinson Mar 15 '18 at 10:22