systemd-analyze calendar: как проверить расписание таймера до включения
Нормализуем OnCalendar, выводим несколько будущих запусков с фиксированной точкой отсчёта и часовым поясом, отдельно разбираем ошибку синтаксиса и пределы применимости команды.

В этой статье
До включения таймера передайте команде systemd-analyze calendar только значение справа от директивы OnCalendar=, без имени директивы и знака равенства. Задайте несколько итераций, фиксированную точку отсчёта и явный часовой пояс. Принимать расписание можно, только если нормализованная форма совпадает с замыслом, абсолютные даты проверены, а команда завершилась с кодом 0. Ненулевой код — повод остановиться, а не включать таймер на пробу.
Проверка ниже выполнена 22 ноября 2026 года в изолированном контейнере Debian 13 с systemd 257 (257.13-1~deb13u1). Права суперпользователя не потребовались: мы не создавали unit-файлы, не запускали службы и не меняли состояние systemd.
Что именно доказывает systemd-analyze calendar
Подкоманда calendar разбирает календарное выражение, печатает его нормализованную форму и вычисляет следующие срабатывания. Это документировано в systemd-analyze(1). Синтаксис тот же, что используется в OnCalendar=. Передавать нужно значение справа от директивы: полная строка с именем и знаком равенства не разбирается. Само значение можно проверить до появления таймера в системе.
Normalized formдолжна отражать нужные дни, время и часовой пояс.Несколько строк
Next elapseдолжны давать ожидаемую последовательность абсолютных дат.Код завершения должен быть равен 0; сообщение об ошибке разбора блокирует дальнейшие действия.
Сначала проверим расписание по будням
Допустим, резервное копирование должно начинаться с понедельника по пятницу в 03:15 по Москве. Фиксируем точку отсчёта, чтобы результат можно было повторить, и просим показать три будущих срабатывания.
systemd-analyze calendar --iterations=3 --base-time='2026-11-22 00:00:00 Europe/Moscow' 'Mon..Fri *-*-* 03:15:00 Europe/Moscow'
Normalized form: Mon..Fri *-*-* 03:15:00 Europe/Moscow
Утилита systemd-analyze приняла выражение и вернула три последовательных рабочих дня. В таблице сохранены абсолютные значения из вывода; относительную строку From now мы не используем как критерий, потому что она зависит от момента запуска самой проверки.
День | Europe/Moscow | UTC |
|---|---|---|
Пн, 23.11.2026 | 03:15 MSK | 00:15 UTC |
Вт, 24.11.2026 | 03:15 MSK | 00:15 UTC |
Ср, 25.11.2026 | 03:15 MSK | 00:15 UTC |

Здесь важны сразу две проверки. Понедельник действительно следует за воскресной точкой отсчёта, а московское время правильно переведено в UTC. Одна удачная дата не обнаружила бы ошибку в диапазоне дней недели, поэтому выводим несколько событий.
Отдельно проверяем часовой пояс
Имена часовых поясов и состав календарного выражения описаны в systemd.time(7). Если задание должно быть привязано к UTC, это лучше написать в самом выражении, а не полагаться на текущий локальный пояс машины.
systemd-analyze calendar --iterations=2 --base-time='2026-11-22 00:00:00 Europe/Moscow' '*-*-* 03:15:00 UTC'
Normalized form: *-*-* 03:15:00 UTC
В этом тесте первое срабатывание пришлось на 22 ноября в 03:15 UTC, то есть в 06:15 MSK, второе срабатывание пришлось на 23 ноября в те же часы. Если ожидалось 03:15 по Москве, выражение с UTC не подходит, хотя синтаксически оно совершенно корректно.
Ошибка разбора должна остановить внедрение
Проверим заведомо неверное выражение с той же точкой отсчёта.
systemd-analyze calendar --base-time='2026-11-22 00:00:00 Europe/Moscow' 'not-a-calendar'
Failed to parse calendar specification 'not-a-calendar': Invalid argument
Код завершения равен 1. Такой результат нельзя заменить визуальной проверкой строки или надеждой на сообщение в журнале после включения: выражение нужно исправить и проверить заново.
Где заканчивается эта проверка
Команда проверяет календарное выражение, но не поведение всего таймера. В systemd.timer(5) отдельно описаны параметры, которые могут изменить фактическое срабатывание.
AccuracySec=задаёт допустимое окно точности, аRandomizedDelaySec=добавляет задержку.Если для параметра
Persistent=задано значениеtrue, календарный таймер при активации может сразу выполнить одно срабатывание, если во время неактивности было пропущено хотя бы одно; такой запуск всё равно подчиняетсяRandomizedDelaySec=.calendarне проверяет unit-файлы, включённость таймера, состояние системных часов, длительность и успех задания.Совпавшее время запуска не доказывает, что резервная копия завершилась и пригодна для восстановления.
По одному признаку выводить рано: успешный разбор значения OnCalendar= подтверждает только расписание, а не весь путь выполнения задачи.
Порядок приёмки таймера
Возьмите из проекта только точное значение справа от
OnCalendar=, не перепечатывая его по памяти.Зафиксируйте версию
systemd, точку отсчёта и ожидаемый часовой пояс.Выведите несколько будущих срабатываний и сверьте нормализованную форму, дни недели, локальное время и UTC.
При ненулевом коде завершения исправьте выражение; не переходите к включению таймера.
Отдельно проверьте структуру timer и service unit, а также влияние
AccuracySec=,RandomizedDelaySec=иPersistent=.После включения, согласованного с ответственным за систему, наблюдайте фактические
NextиLast, журнал службы и результат самой задачи.
Расписание готово к следующему этапу, когда утилита systemd-analyze принимает выражение, несколько абсолютных дат совпадают с ожидаемыми днями и поясом, а ограничения полного таймера учтены отдельно. Только после этого календарная строка перестаёт быть догадкой и становится проверенным входным условием.
Before enabling the timer, pass the systemd-analyze calendar command only the value to the right of the OnCalendar= directive, without the directive name or the equals sign. Specify several iterations, a fixed reference point, and an explicit time zone. Accept the schedule only if the normalized form matches the intent, absolute dates are verified, and the command exits with code 0. A non-zero exit code is a reason to stop, not to enable the timer for a trial run.
The check below was performed on November 22, 2026, in an isolated Debian 13 container with systemd 257 (257.13-1~deb13u1). Superuser privileges were not required: we did not create unit files, start services, or alter the state of systemd.
What systemd-analyze calendar specifically demonstrates
The calendar subcommand parses a calendar expression, prints its normalized form, and calculates the next triggers. This is documented in systemd-analyze(1). The syntax is the same as that used in OnCalendar=. You must pass the value to the right of the directive: the full line with the name and equals sign is not parsed. The value itself can be verified before the timer appears in the system.
Normalized formmust reflect the correct days, time, and time zone.Several lines of
Next elapseshould yield the expected sequence of absolute dates.The exit code must be 0; a parsing error message blocks further actions.
First, let's check the schedule for weekdays
Assume the backup should start from Monday to Friday at 03:15 Moscow time. We fix the reference point so the result can be reproduced, and ask to show the next three triggers.
systemd-analyze calendar --iterations=3 --base-time='2026-11-22 00:00:00 Europe/Moscow' 'Mon..Fri *-*-* 03:15:00 Europe/Moscow'
Normalized form: Mon..Fri *-*-* 03:15:00 Europe/Moscow
The systemd-analyze utility parsed the expression and returned three consecutive working days. The table preserves absolute values from the output; we do not use the relative row From now as a criterion because it depends on the exact moment the check was run.
Day | Europe/Moscow | UTC |
|---|---|---|
Mon, 23.11.2026 | 03:15 MSK | 00:15 UTC |
Tue, 24.11.2026 | 03:15 MSK | 00:15 UTC |
Wed, 25.11.2026 | 03:15 MSK | 00:15 UTC |

Two checks are important here. Monday indeed follows the Sunday reference point, and Moscow time is correctly converted to UTC. A single successful date would not have revealed an error in the day-of-week range, so we output several events.
Separately check the time zone
Time zone names and the structure of the calendar expression are described in systemd.time(7). If a job must be bound to UTC, it is better to write this directly in the expression rather than relying on the machine's current local time zone.
systemd-analyze calendar --iterations=2 --base-time='2026-11-22 00:00:00 Europe/Moscow' '*-*-* 03:15:00 UTC'
Normalized form: *-*-* 03:15:00 UTC
In this test, the first trigger occurred on November 22 at 03:15 UTC, which is 06:15 MSK; the second trigger occurred on November 23 at the same time. If 03:15 Moscow time was expected, the UTC expression is unsuitable, even though it is syntactically correct.
A parsing error must stop the deployment
Let us test a clearly invalid expression using the same reference point.
systemd-analyze calendar --base-time='2026-11-22 00:00:00 Europe/Moscow' 'not-a-calendar'
Failed to parse calendar specification 'not-a-calendar': Invalid argument
The exit code is 1. Such a result cannot be replaced by visual inspection of the string or hope for a log message after enabling: the expression must be corrected and tested again.
Where does this check end
The command validates the calendar expression but not the behavior of the entire timer. Parameters that may affect the actual trigger are described separately in systemd.timer(5).
AccuracySec=sets the allowable precision window, whileRandomizedDelaySec=adds a delay.If the parameter
Persistent=is set totrue, the calendar timer may trigger immediately upon activation if at least one activation was missed during inactivity; such a launch still adheres toRandomizedDelaySec=.calendardoes not check unit files, timer enablement, system clock status, task duration, or task success.A matching start time does not prove that the backup completed successfully or is suitable for recovery.
Drawing conclusions from a single indicator is premature: successful parsing of the OnCalendar= value confirms only the schedule, not the entire task execution path.
Timer acceptance order
Extract only the exact value to the right of
OnCalendar=from the project; do not transcribe it from memory.Record the version of
systemd, the reference point, and the expected time zone.Output several future triggers and verify the normalized form, days of the week, local time, and UTC.
If the exit code is non-zero, correct the expression; do not proceed to enable the timer.
Separately verify the structure of the timer and service unit, as well as the influence of
AccuracySec=,RandomizedDelaySec=, andPersistent=.After enabling, in coordination with the system owner, monitor the actual
NextandLast, the service log, and the task result.
The schedule is ready for the next stage when the systemd-analyze utility accepts the expression, several absolute dates match the expected days and time zone, and full timer constraints are accounted for separately. Only then does the calendar string cease to be a guess and become a verified input condition.





Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.