I have a cronjob that runs a script on the 20th day of the month at 6 AM:
0 6 20 * * /opt/example.sh
This works as intended, but I'd like to adjust this, so the script is executed earlier, if the 20th falls on a Saturday or Sunday. For example:
On February 20 2021, the script is scheduled to run, however this is a Saturday, so instead it is executed on Friday the 19th. Likewise, on February 20 2022, the script is scheduled to run, yet this is a Sunday, so instead it is executed on Friday the 18th.
I was not able to identify any options or hacks to accomplish this with cronjob itself. I was hoping to find some trick to use with the usable alternative single values (i.e. SUN for Sunday in the crontab).
I assume this needs to implemented in the script itself.
For example I could run it on the 18th and delay the execution (sleep) within the script, until the 20th unless the weekend is reached. This seems very error prone to me. Alternatively, I had the idea to schedule the execution for the 18th, 19th and 20th and check the date in the script, if it's within my intentions to be executed or not.
Is there any way to implement this with cron itself?
OnCalendar=
events, which trigger when any of them matches. You can specify one event for Mondays to Fridays on the 20th:OnCalendar='Mon-Fri *-*-20 00:00:00'
, and another one for Fridays on the 18th and 19th:OnCalendar='Fri *-*-18-19 00:00:00'
.*-*-18-19
should be*-*-18..19
.