2

Suppose I want to run the command notify-send "invoked" "$(date)" every 5 seconds using systemd timers.

I know how to create a corresponding unit file and a timer file, then enable the timer for user, but I want a pure CLI-based solution.

I want to simply do the above in commandline without needing to create 2 files. Something like: systemd-blah enable my_command --every 5s.

2
  • Comment, because my answer is a bit off target: why not while true; do notify-send ...; sleep 5; done?
    – Malik
    Mar 11, 2022 at 7:26
  • @Malik same reason as answers provided here. I'm starting multiple tasks like this and I want to get a list of tasks in queue using systemd's functionality. BTW, the same thing could be achieved with watch: watch -n5 my_command Mar 11, 2022 at 9:39

1 Answer 1

2

You're looking for systemd-run, specifically one of the timer-related options: --on-active=, --on-boot=, --on-startup=, --on-unit-active=, --on-unit-inactive= and --on-calendar=.

Using a monotonic timer:

systemd-run --user --on-startup=0s --on-unit-inactive=5s --timer-property=AccuracySec=100ms sh -c 'notify-send "invoked" "$(date)"'

Using a calendar (wall-clock) timer:

systemd-run --user --on-calendar='*:*:0/5' --timer-property=AccuracySec=100ms sh -c 'notify-send "invoked" "$(date)"'

Note that the default timer accuracy is 1 minute, which is too coarse for timer intervals as short as 5 seconds.

Other useful arguments to systemd-run you will likely want to use include --unit/-u (for naming the unit) and --description (for providing a description that is shown by systemd, in the journal, etc. instead of the triggered command).

The transient systemd units behave just like regular ones. Once they are no longer referenced anywhere, they are garbage collected as described here.

2
  • Thanks! How can I make it persistent (survive restart/shutdown)? May 23, 2022 at 22:02
  • 1
    Either put systemd-run --user --unit=foo ... in your shell's init script (discarding the error message shown if the unit already exists) or better, create the appropriate units in ~/.config/systemd/user/ yourself (i.e. foo.service and an associated foo.timer). For detailed information I recommend looking at the related Arch Linux Wiki article. Most information in that article is not specific to Arch.
    – Max Truxa
    May 24, 2022 at 9:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .