Course contentsShow
← Linux
Lesson 178 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Systemd Timer Scheduling

Replace brittle cron jobs with resilient unit-based task scheduling.

In this lesson, you will learn how to replace fragile cron jobs with robust systemd timers to ensure your background tasks are scheduled reliably within the system’s lifecycle.

The Problem with Cron

You’ve likely used cron before, but it has a major drawback: it is "fire and forget." If a machine is powered down when a cron job is scheduled, the task is simply skipped. Furthermore, cron jobs lack the sophisticated dependency management and logging features that come native to the systemd ecosystem.

Transitioning to Systemd Timers

To move from cron to systemd, you don't just create a single file; you pair a Service Unit with a Timer Unit.

  1. The Service Unit (backup.service): This defines what happens. It uses the systemd service integration patterns you learned previously.

    [Service]
    ExecStart=/usr/local/bin/my_backup_script.sh
    
  2. The Timer Unit (backup.timer): This defines when it happens. Instead of brittle strings like 0 2 * * *, you use semantic time syntax.

    [Timer]
    OnCalendar=daily
    AccuracySec=1h
    Persistent=true
    

Why This is Resilient

The Persistent=true directive is the "secret sauce." If your system was off during the scheduled time, systemd will trigger the job immediately upon boot. Unlike cron, these timers are treated as first-class citizens of the system state. You can monitor their execution using systemctl list-timers, check their output via journalctl -u backup.service, and even set up dependency constraints—ensuring, for example, that your backup script only runs after the network is fully online.

By encapsulating your tasks this way, you move away from hidden environment variables and mysterious shell paths, opting instead for a deterministic execution environment that respects system state snapshots and hardware resource limits. It turns a "blind trigger" into a managed lifecycle event.

Key Takeaway: Systemd timers provide reliable, persistent task scheduling that integrates deeply with system state, ensuring your scripts run exactly when intended, even across reboots.