Skip to content

Instantly share code, notes, and snippets.

@goncalor
Last active July 7, 2024 00:16
Show Gist options
  • Save goncalor/65c27f372fbd52d996140a22e320bcca to your computer and use it in GitHub Desktop.
Save goncalor/65c27f372fbd52d996140a22e320bcca to your computer and use it in GitHub Desktop.
cron-like systemd unit notes

cron-like systemd unit

  1. Create myunit.service. Only [Service] is needed, with an ExecStart=

  2. Create myunit.timer. It needs [Timer] with an OnCalendar= or similar. It needs [Install] with WantedBy=timers.target

  3. Enable both units. The .service unit will issue a warning due to missing [Install]. This is not a problem

     systemctl --user enable $PWD/myunit.service
     systemctl --user enable $PWD/myunit.timer
    

Now you can start the timer when you want, for the .service to be executed according to schedule.

To verify the status of timers, use systemctl list-timers.

Starting on boot

At this point, the timer will only start once the user logs in (if installed for root it should start on boot). If you want the timer to start automatically on boot:

loginctl enable-linger [user]

No need for persistence

If you want to run a service on a schedule (or once) only temporarily (lose it after poweroff), you can use systemd-run. The .service and .timer units are created automatically for you. For example:

systemd-run --user [--unit=myunit] --on-calendar=hourly /bin/touch /tmp/test
[Unit]
[Service]
ExecStart="/bin/touch" "/tmp/test"
[Unit]
[Timer]
OnCalendar=minutely
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment