Systemd/timers: Difference between revisions

From NixOS Wiki
imported>Papanito
Add some more details about timers
imported>Papanito
m add missing space
Line 38: Line 38:
</syntaxHighlight>
</syntaxHighlight>


Some more examples can be found [https://wiki.archlinux.org/title/Systemd/Timers here] and[https://www.freedesktop.org/software/systemd/man/systemd.timer.html here].
Some more examples can be found [https://wiki.archlinux.org/title/Systemd/Timers here] and [https://www.freedesktop.org/software/systemd/man/systemd.timer.html here].


== Usage ==
== Usage ==

Revision as of 13:18, 11 September 2023

Timers are systemd unit files whose name ends in .timer that control .service files or events. Timers can be used as an alternative to cron. Timers have built-in support for calendar time events, monotonic time events, and can be run asynchronously.

Configuration

Following example timer runs a systemd unit every 5 minutes which invokes a bash script

systemd.timers."hello-world" = {
  wantedBy = [ "timers.target" ];
    timerConfig = {
      OnBootSec = "5m";
      OnUnitActiveSec = "5m";
      Unit = "hello-world.service";
    };
};

systemd.services."hello-world" = {
  script = ''
    set -eu
    ${pkgs.coreutils}/bin/echo "Hello World"
  '';
  serviceConfig = {
    Type = "oneshot";
    User = "root";
  };
};

The following example would starts once a day (at 12:00am). When activated, it triggers the service immediately if it missed the last start time (option Persistent=true), for example due to the system being powered of

...
  serviceConfig = {
      OnCalendar = "daily";
      Persistent = true; 
  };
};

Some more examples can be found here and here.

Usage

List active timers and their current state

systemctl list-timers

Manually run service once for testing purpose

systemctl start hello-world