2

I want to run a service file on the last day of every month. How to configure this? I am referring the Systemd.timers but not able to find the right approach.

Additionally will it be possible to add another configuration to run on the last working day of the month also? (days other than sun and sat)

5

As of version 233, systemd supports using "~" in its calendar syntax to specify dates relative to the end of the month.

OnCalendar=*-02~03 means the third last day in February (the 26th or 27th, depending on whether or not it's a leap year)

Mon *-05~07/1 and Mon *-05~01..07 are synonyms for the last Monday in May.

https://github.com/systemd/systemd/blob/v233/NEWS#L174

1

The simplest solution is probably to use a timer that runs every day, and checks if tomorrow is the 1st of the month. Something like:

mytimer.timer:

[Unit]
Description=run mytimer.service daily at 6am
[Timer]
OnCalendar=6:00
Persistent=true
[Install]
WantedBy=timers.target

mytimer.service:

[Unit]
Wants=mytimer.timer
Description=run on last day of month
[Service]
Type=oneshot
ExecStart=/bin/bash -c '[ $(date --date=tomorrow +%d) -eq 1 ] && \
                        /bin/myscript'

For the last working day of the month, I calculate it as: look 3 days in the future, and check if the date is the 3rd and the day is Thursday to Monday inclusive, or the date is the 1st or 2nd and the day is Monday. The equivalent bash test using date and %w for the day of the week (0=Sunday) would be

[[ $(date --date=+3days +%d%w) =~ 03[45601]|011|021 ]]
  • I though about this solution, in my case I thought of running it on 28,29,30 and 31 of a month and determine. But it wont be optimistic, hence I have raised this question here. Does systemd timer configuration has any regex to determine the last day? – Dinesh P.R. Aug 29 '16 at 8:43
  • I dont know of any "last day" pattern. Sometimes a simple solution is to be preferred, as optimisation can introduce subtle failures, and be hard to maintain by a future person. For something that runs once a day, I dont think you should try too hard. – meuh Aug 29 '16 at 8:52
  • I added a last working day of the month calculation. – meuh Aug 29 '16 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.