Systemd/timers/ru: Difference between revisions

From NixOS Wiki
Unabomberlive (talk | contribs)
Created page with "Таймеры - это файлы модулей systemd, чье имя заканчивается на .timer, которые управляют .service файлами или событиями. Таймеры могут быть использованы в качестве альтернативы <code>cron</code>."
Tags: Mobile edit Mobile web edit
FuzzyBot (talk | contribs)
Updating to match new version of source page
Tags: Mobile edit Mobile web edit
 
(5 intermediate revisions by one other user not shown)
Line 2: Line 2:


Таймеры - это файлы модулей systemd, чье имя заканчивается на .timer, которые управляют .service файлами или событиями. Таймеры могут быть использованы в качестве альтернативы <code>cron</code>.
Таймеры - это файлы модулей systemd, чье имя заканчивается на .timer, которые управляют .service файлами или событиями. Таймеры могут быть использованы в качестве альтернативы <code>cron</code>.
Таймеры имеют встроенную поддержку событий, основанных на календаре, и монотонных временных событий, а также могут запускаться асинхронно.
<span id="Configuration"></span>
<span id="Configuration"></span>
== Настройка ==
== Настройка ==
Line 26: Line 27:
};
};
</syntaxHighlight>
</syntaxHighlight>
<div lang="en" dir="ltr" class="mw-content-ltr">
 
The following example 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 off.
 
</div>
Alternatively here, avoid quotes when calling for the binary and its command options:
 
<syntaxHighlight lang="nix">
${pkgs.foo}/bin/foo command-options
</syntaxHighlight>
 
This will yield the same result as running
<syntaxhighlight lang="bash">
foo command-options
</syntaxhighlight>
in your terminal.
 
====Using the <code>systemd.services.&lt;name&gt;.startAt</code> shorthand====
 
If you only want a service to execute at an interval and don't plan to configure the timer much more, you can use the <code>systemd.services.&lt;name&gt;.startAt</code> option. This will have the underlying systemd module in nixpkgs create the timer for you, and set its <code>OnCalendar</code> field. Note that the semantics for <code>OnCalendar</code> are different to <code>OnUnitActiveSec</code>.
 
This example shows the previous <code>hello-world</code> service configured with <code>startAt</code>, running every 5 minutes.
 
<syntaxHighlight lang="nix">
systemd.services."hello-world" = {
  script = ''
    set -eu
    ${pkgs.coreutils}/bin/echo "Hello World"
  '';
  serviceConfig = {
    Type = "oneshot";
    User = "root";
  };
  startAt = "*:0/5";
};
</syntaxHighlight>
 
====Running timer on a schedule====
 
Следующий пример запускается один раз в день (в 12:00). При активации он запускает службу немедленно, если пропущено время последнего запуска (опция Persistent=true), например, из-за отключения питания системы.
<syntaxHighlight lang="nix">
<syntaxHighlight lang="nix">
...
...
Line 42: Line 77:
<span id="Usage"></span>
<span id="Usage"></span>
== Использование ==
== Использование ==
<div lang="en" dir="ltr" class="mw-content-ltr">
Список активных таймеров и их текущее состояние:
List active timers and their current state:
</div>
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
systemctl list-timers
systemctl list-timers
</syntaxhighlight>
</syntaxhighlight>
<div lang="en" dir="ltr" class="mw-content-ltr">
Запустите службу вручную один раз в целях тестирования:
Manually run a service once for testing purposes:
</div>
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
systemctl start hello-world
systemctl start hello-world
</syntaxhighlight>
</syntaxhighlight>
[[Category:systemd]]
[[Category:systemd]]

Latest revision as of 09:28, 17 September 2024

Таймеры - это файлы модулей systemd, чье имя заканчивается на .timer, которые управляют .service файлами или событиями. Таймеры могут быть использованы в качестве альтернативы cron. Таймеры имеют встроенную поддержку событий, основанных на календаре, и монотонных временных событий, а также могут запускаться асинхронно.

Настройка

Следующий пример таймера запускает каждые 5 минут юнит systemd, который вызывает сценарий bash.

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";
  };
};


Alternatively here, avoid quotes when calling for the binary and its command options:

${pkgs.foo}/bin/foo command-options

This will yield the same result as running

foo command-options

in your terminal.

Using the systemd.services.<name>.startAt shorthand

If you only want a service to execute at an interval and don't plan to configure the timer much more, you can use the systemd.services.<name>.startAt option. This will have the underlying systemd module in nixpkgs create the timer for you, and set its OnCalendar field. Note that the semantics for OnCalendar are different to OnUnitActiveSec.

This example shows the previous hello-world service configured with startAt, running every 5 minutes.

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

Running timer on a schedule

Следующий пример запускается один раз в день (в 12:00). При активации он запускает службу немедленно, если пропущено время последнего запуска (опция Persistent=true), например, из-за отключения питания системы.

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

More examples can be found at the Arch Wiki and at the systemd.timer manpage.

Использование

Список активных таймеров и их текущее состояние:

systemctl list-timers

Запустите службу вручную один раз в целях тестирования:

systemctl start hello-world