Systemd – Timer Units Mimicking Anacron Behavior

cronsystemd

I need to write a timer unit for a machine which is turned off frequently (e.g. classical desktop setup). This timer unit needs to be activated regularly, but not very often (e.g. weekly, monthly).

I did find some approaches, but they all don't really fit:

  • According to the man pages, only the OnBootSec and the OnStartupSec directives will be activated if the configured point of time is in the past. I found as well some examples using a combination of these with OnActiveSec to define a regular event. The problem is: Every time the machine is booted the timer will activate the configured unit. If you got a timer which should run ONCE a week/month that is far too often. For example: I don't want to get my logs rotated three times a day!

  • Solutions with the OnCalendar directive. If the machine is powered off at the configured point in time (mostly midnight because if you omit the hour in the time specification it defaults to 00:00:00) the timer won't be activated after the next boot. That's at least how I got it. Is that right?

Are timer with calendar events activated right after the next startup if the configured time is in the past? If not, is there a workaround to get such a behaviour?

Best Answer

This feature has already been implemented in systemd (ver >= 212) using the Persistent= directive so you just need to insert Persistent=true in the unit file while using OnCalendar= directive to establish the date/time to run the job.

Persistent=

Takes a boolean argument. If true, the time when the service unit was last triggered is stored on disk. When the timer is activated, the service unit is triggered immediately if it would have been triggered at least once during the time when the timer was inactive. This is useful to catch up on missed runs of the service when the machine was off. Note that this setting only has an effect on timers configured with OnCalendar=.

Related Question