Beyond Cron: How to Schedule and Monitor Tasks with systemd Timers

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Cron has been solving a very specific need in Linux for decades: running commands periodically. It is simple, available on virtually every distribution, and, for many tasks, remains a perfectly valid solution.

However, when those tasks become part of standard server operations, needs arise that go beyond specifying a time in a crontab:

  • Running jobs under specific users and conditions.
  • Managing service dependencies.
  • Catching up on missed calendar executions after a server downtime.
  • Checking the status and logs of each run from a single centralized place.
  • Setting timeouts and actions for specific failure scenarios.

In previous articles, we explored how to detect errors in scheduled tasks, verify that backups can actually be restored, and detect jobs that stop running without producing errors.

Now let’s explore another tool available across many Linux distributions: systemd timers.

This is not about declaring cron obsolete. Both mechanisms can coexist and have valid use cases. The difference is that systemd integrates task scheduling directly into the same system that manages your server services.

1. What Are systemd Timers?

A systemd timer is a unit that activates another unit when a time condition is met.

Unlike cron, where we typically declare both the schedule and the command in the same entry, systemd separates these responsibilities across two files:

  • .service: defines what should run, under which user, and under what conditions.
  • .timer: defines when the service should be activated.

For example, we might have a service named backup-postgresql.service and a timer named backup-postgresql.timer.

The timer does not need to know the details of the backup. Its sole responsibility is to trigger the service at the specified time. The service, in turn, does not need to know whether it was started manually, triggered by a timer, or invoked by another systemd unit.

This separation makes it easier to reuse tasks, modify schedules without touching scripts, and leverage the monitoring capabilities built into the system itself.

2. Building Our First systemd Timer

Let’s use the same example from previous articles: generating a daily PostgreSQL backup.

Suppose we already have a script located at:

/opt/scripts/backup-postgresql.sh

The script generates and validates the backup, logs the outcome, and returns a non-zero exit code whenever an error occurs.

First, we create the service unit:

# /etc/systemd/system/backup-postgresql.service

[Unit]
Description=Respaldo de PostgreSQL

[Service]
Type=oneshot
User=backup
Group=backup
ExecStart=/opt/scripts/backup-postgresql.sh
UMask=0077
TimeoutStartSec=45min

Let’s break down the most important options:

  • Type=oneshot: indicates that the service runs a task and exits. We are not starting a long-running daemon process.
  • User and Group: define the user and group under which the job executes.
  • ExecStart: specifies the command to execute.
  • UMask=0077: sets restrictive permissions for files created by the process.
  • TimeoutStartSec=45min: defines a timeout for completing the service execution.

It is essential that the backup user has the necessary permissions to execute the script, access PostgreSQL credentials, and write to the backup directory. If you use a .pgpass file, remember that PostgreSQL requires it to have restrictive permissions, typically 0600.

Now we create the timer:

# /etc/systemd/system/backup-postgresql.timer

[Unit]
Description=Ejecutar respaldo diario de PostgreSQL

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

When the .timer file and the .service file share the exact same base name (backup-postgresql), systemd binds them automatically. You would only need to add the Unit=other-name.service directive if you wanted to trigger a unit with a different name.

The OnCalendar directive specifies that the service must run every day at 02:00.

Persistent=true allows systemd to catch up on a missed calendar trigger if the timer was inactive when it was due. We will look closer at why this is particularly useful in a moment.

Finally, reload the units and enable the timer:

sudo systemctl daemon-reload
sudo systemctl enable --now backup-postgresql.timer

With this, the job is scheduled. We did not have to alter the script or embed scheduling logic inside it.

An added benefit is that we can run the service manually whenever needed:

sudo systemctl start backup-postgresql.service

The exact same service unit is used for both scheduled and manual executions.

3. Scheduling Tasks with OnCalendar

If you are coming from cron, the first thing you probably want to know is how to express your typical schedules using OnCalendar.

systemd’s syntax is different, but it allows you to describe dates and times in a very readable manner. Here are some practical equivalents:

Cronsystemd OnCalendarDescription
0 2 * * **-*-* 02:00:00Every day at 02:00
*/15 * * * **:0/15Every 15 minutes
0 6 * * 1Mon *-*-* 06:00:00Every Monday at 06:00
0 0 1 * **-*-01 00:00:00The first day of every month

We can also express schedules with greater flexibility:

[Timer]
OnCalendar=Mon..Fri 08:30:00
RandomizedDelaySec=10min

In this example, the service runs Monday through Friday starting at 08:30, applying a randomized delay of up to 10 minutes (RandomizedDelaySec=). This directive is very useful when multiple servers or tasks share the exact same execution time and you want to avoid simultaneous spikes in CPU, disk, or network usage.

There is another crucial detail: systemd does not guarantee that the timer will trigger at the exact second specified. The AccuracySec= directive establishes an accuracy window, which defaults to one minute.

We can reduce it when higher precision is required:

[Timer]
OnCalendar=*-*-* 02:00:00
AccuracySec=1s

This narrows the event coalescing window, but it does not turn systemd into a real-time scheduler. System load and other factors can still affect the actual execution time.

It helps to distinguish between both directives:

  • AccuracySec= allows systemd to group nearby events together to reduce unnecessary system wakeups.
  • RandomizedDelaySec= introduces a random delay to spread executions out and prevent multiple jobs from colliding.

If both are used, the random delay is applied first, and systemd can then adjust execution within the accuracy window.

A handy tool for testing these expressions is systemd-analyze calendar, which lets you verify how systemd parses a given schedule:

systemd-analyze calendar "Mon..Fri 08:30:00"

The command displays how the expression is normalized and shows the next time it will trigger.

We can also inspect upcoming runs for our configured timer:

systemctl list-timers backup-postgresql.timer

Other Types of Timers

Not all tasks need to run at a specific calendar time. Some should trigger after system boot or after a certain elapsed time since a previous run. For these scenarios, systemd provides other directives:

DirectiveBehavior
OnBootSec=Time elapsed after system boot
OnStartupSec=Time elapsed after the service manager started
OnActiveSec=Time elapsed after activating the timer
OnUnitActiveSec=Time elapsed since the service unit was last activated
OnUnitInactiveSec=Time elapsed since the service unit became inactive

For example, if we want to run a sync job five minutes after server boot and repeat it every fifteen minutes since its last activation:

[Timer]
OnBootSec=5min
OnUnitActiveSec=15min
Unit=sincronizar-datos.service

This lets you schedule tasks relative to the system lifecycle, rather than purely by wall-clock dates and times.

There is a notable difference between OnUnitActiveSec and OnUnitInactiveSec: the former counts from when the unit was activated, whereas the latter counts from when it became inactive. In a oneshot task that exits after finishing its work, this distinction can alter the actual interval between runs.

Keep in mind that if the timer is started after the first five minutes following system boot have already passed, OnBootSec=5min may fire immediately. Subsequent intervals will then follow OnUnitActiveSec.

4. An Important Feature: Persistent=true

One of the most interesting advantages of systemd timers is their ability to catch up on certain calendar executions that were missed while the timer was inactive.

Let’s revisit the backup scenario:

  • The backup is scheduled daily at 02:00.
  • The server is powered off during that hour.
  • The machine boots back up at 05:00.
  • The timer detects that a scheduled run was missed and triggers the service.

This behavior is enabled by:

Persistent=true

When used alongside OnCalendar, Persistent=true causes systemd to store a timestamp on disk indicating when the service was last triggered. When the timer is enabled or starts up, it checks whether a calendar activation was missed during the inactive period and, if so, triggers the service once.

It is important to understand what this means: Persistent is not a work queue.

If a server stays powered off for five days, systemd will not run five consecutive backups upon booting up. The option allows catching up on a single missed calendar event, not replaying all historical runs that could not execute.

Nor does it mean that tasks that failed during execution are automatically recovered. If the service started and returned an error, that is a separate issue that must be addressed using error-handling mechanisms.

This feature is particularly valuable for tasks that must run at least once following a server interruption, though it is no substitute for a dedicated catch-up strategy designed for jobs that must process every individual missing interval.

5. How to Monitor Tasks

So far, we have seen how to schedule a task and catch up on missed runs. But we also need visibility into what is happening with them.

Here systemd holds a major advantage: timers and services belong to the same unit manager.

We can list all timers known to systemd:

systemctl list-timers --all

The output includes key information such as:

  • Next scheduled run.
  • Time remaining until next activation.
  • Last activation time.
  • Associated service unit.

To inspect a specific timer:

systemctl status backup-postgresql.timer

And to check the service that runs the backup:

systemctl status backup-postgresql.service

We can also inspect the logs of its past runs:

journalctl -u backup-postgresql.service

If we want to check the most recent messages:

journalctl -u backup-postgresql.service -n 50

Or follow logs in real time:

journalctl -fu backup-postgresql.service

This allows us to centralize logs without having to manually configure separate log outputs for every individual task.

Understanding the State of a oneshot Service

A common source of confusion when starting with systemd for scheduled tasks is service state.

When a Type=oneshot service finishes successfully (without RemainAfterExit=yes), it returns to the inactive state. That does not mean it failed; it is the expected behavior because the task completed and no active processes remain running. Conversely, if the script fails (returns a non-zero exit code), the unit state transitions to failed.

To precisely inspect the result of the last run, we can query the unit properties:

systemctl show backup-postgresql.service \
  -p Result \
  -p ExecMainStatus \
  -p ExecMainCode \
  -p ActiveState \
  -p InactiveEnterTimestamp

Key properties include:

  • Result: result recorded by systemd for the execution (e.g., success or exit-code).
  • ExecMainStatus: exit code of the main process.
  • ExecMainCode: indicates how the process terminated.
  • ActiveState: current state of the unit (inactive after success, failed after an error).
  • InactiveEnterTimestamp: timestamp when the unit ceased to be active.

6. Error Handling and Execution Management

One advantage of service units is that we can define how systemd should behave when a task fails.

If the script returns a non-zero exit code, systemd records the failure and notes the outcome of the activation. We can verify this with:

systemctl status backup-postgresql.service

And review the details in the journal:

journalctl -u backup-postgresql.service -n 50

Keep one detail about journald in mind: by default, systemd captures both stdout and stderr from the script at info priority. Therefore, if you filter using journalctl -u backup-postgresql.service -p err, you will see the failure message generated by systemd itself, but you might miss error messages written by your script to stderr (unless the script explicitly uses syslog level prefixes).

We can also configure additional actions right inside the .service file.

Setting Execution Timeouts

In our example, we already used:

TimeoutStartSec=45min

This prevents a task from running indefinitely if it hangs and fails to exit on its own. When the configured limit is exceeded, systemd marks the activation as failed and triggers the configured termination procedure for the unit.

This is a critical safeguard for jobs that rely on external services, network connections, or processes that might otherwise hang indefinitely.

An extra detail: for Type=oneshot services, the startup timeout is disabled by default. That is why it is especially important to set TimeoutStartSec= explicitly whenever running tasks that might hang.

Triggering an Action on Service Failure

Another capability is using OnFailure=:

[Unit]
Description=Respaldo de PostgreSQL
OnFailure=backup-postgresql-alert.service

[Service]
Type=oneshot
User=backup
Group=backup
ExecStart=/opt/scripts/backup-postgresql.sh
TimeoutStartSec=45min

In this scenario, if the service transitions into a failed state, systemd activates another unit responsible for handling notifications.

backup-postgresql-alert.service must exist and contain the necessary logic to send the alert—for instance, via a script using email or a notification API. It is a clean way to separate the primary workload from error reporting.

What About Restart=on-failure?

In long-running services, it is common to see configurations like Restart=on-failure. In Type=oneshot units, systemd allows this option, but it does not support Restart=always or Restart=on-success.

While automatic retries can be configured for certain failures, doing so requires caution. A process synchronizing data might have completed partial operations before failing, and re-running it without guaranteeing idempotency can introduce duplicate or inconsistent data.

For scheduled tasks, the most prudent approach is to first evaluate which operations are safe to repeat. Use Restart=on-failure when a well-defined retry strategy exists, or record the failure and report it via OnFailure= for explicit handling.

What Happens if the Service Is Already Running?

Imagine the backup takes longer than usual and the next scheduled run arrives.

systemd will not start a second concurrent instance of the same service while the previous unit remains active. This applies both to timer triggers and manual executions made via systemctl start.

A trigger that coincides with an already active service will neither create an additional instance nor interrupt the process currently running. Therefore, if a task can take longer than its scheduled interval, design the schedule with its duration in mind.

However, this does not guard against direct script executions outside systemd (for example, if someone runs /opt/scripts/backup-postgresql.sh manually from a shell or from another system). If you need to ensure mutual exclusion in those scenarios as well, using tools like flock inside the script remains recommended.

7. Security and Task Sandboxing

Another benefit of defining tasks as systemd units is the fine-grained control over execution conditions. For example:

[Service]
Type=oneshot
User=backup
Group=backup
WorkingDirectory=/opt/scripts
EnvironmentFile=/etc/default/backup-postgresql
ExecStart=/opt/scripts/backup-postgresql.sh
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=full

Notable options include:

  • User and Group: prevent tasks from unnecessarily running as root.
  • WorkingDirectory: sets the working directory.
  • EnvironmentFile: loads environment variables from an external file.
  • NoNewPrivileges: prevents the process from gaining additional privileges via mechanisms like setuid or setgid bits.
  • PrivateTmp: provides a private temporary space for the service.
  • ProtectSystem=full: mounts system directories like /usr, /boot, and /etc as read-only.

Exercise caution with access restrictions. If the script needs to write to a protected location, you must explicitly configure exemptions (for example, with ReadWritePaths=). Likewise, environment variable files and credentials must have appropriate file permissions.

This is not about applying every available option blindly without testing. The goal is to leverage systemd sandboxing to match the actual security requirements of each task.

8. Cron or systemd Timers: Which Should You Use?

After reviewing the capabilities of both tools, the right choice depends on the workload and the environment where it will run.

RequirementRecommended Choice
Run a simple command periodicallyCron
Schedule tasks integrated with systemd servicessystemd timers
Catch up on calendar runs missed during downtimesystemd timers with Persistent=true
Inspect centralized logssystemd and journald
Define users, dependencies, and sandboxingsystemd
Run tasks on systems without systemdCron or an alternative scheduler
Detect when an entire server stops respondingExternal monitoring

Cron remains a solid choice for simple scripts, especially when portability is required or when operating on systems without systemd.

On the other hand, if you manage a modern server running systemd, timers let you leverage existing infrastructure and enjoy integrated management for scheduled tasks.

You do not have to choose strictly one or the other. You can keep cron for lightweight jobs and use systemd units for processes requiring greater control.

Scheduling Is Not the Same as Monitoring

With systemd timers, we gain powerful tools to schedule tasks, catch up on missed executions, and inspect run outcomes. Still, there is a fundamental difference between knowing that a service exited cleanly and confirming that the job produced the expected result.

A backup can finish with an exit code of zero and still be unrestorable. A synchronization script can complete without errors and leave data incomplete. And if the server stops responding entirely, systemd cannot send an alert from that host.

That is why the tools we have covered throughout this series remain complementary:

  • Scheduling: cron or systemd timers determine when jobs execute.
  • Error handling: exit codes and logs identify failed runs.
  • Heartbeats: an external monitor detects tasks that stopped sending signals.
  • Result validation: confirms that the job actually fulfilled its intended purpose.

You don’t need to turn every server into an observability platform to achieve this. You can start with well-defined systemd units, centralized logging, and external monitoring for your critical tasks.

Scheduling sets the work in motion. Monitoring tells you if it executed. And validation ensures that it actually accomplished what it was supposed to do.