Exercise

Scheduling a Timer Unit Exercise

Task

Take the service you already wrote and put it on a schedule, then make that schedule survive the machine being switched off. This is the same catch-up behavior anacron gives cron, done per unit.

Host
servera
Prerequisite exercise
A Robust Sync Service
Schedule
every two minutes to test, then daily
Must survive
the machine being switched off
  1. Confirm the service still works

    Become root and run the unit from the previous exercise once by hand.

    sudo -i
    systemctl start etc-sync.service
    systemctl is-failed etc-sync.service
  2. Write a timer for it

    A timer takes the name of the service it triggers, with a .timer suffix. That matching name is the whole link between them.

    vim /etc/systemd/system/etc-sync.timer
    [Unit]
    Description=Sync /etc to workstation on a schedule
    
    [Timer]
    OnCalendar=*:0/2
    
    [Install]
    WantedBy=timers.target
    systemctl daemon-reload
  3. Enable the timer, not the service

    systemctl enable --now etc-sync.timer
    systemctl list-timers etc-sync.timer --no-pager

    NEXT is when it fires next, and ACTIVATES names the service it will start.

  4. Watch it fire

    Wait for the next even minute, then look again.

    systemctl list-timers etc-sync.timer --no-pager
    journalctl -u etc-sync.service -n 5 --no-pager

    LAST and PASSED now show a real run.

  5. Make it survive downtime

    First look at what systemd is recording about this timer.

    ls -l /var/lib/systemd/timers/

    There is no stamp file, because nothing is tracking the last run yet. Change the schedule to daily and ask for persistence.

    vim /etc/systemd/system/etc-sync.timer

    Search with /OnCalendar, replace that line with C, then o to open a line below it:

    OnCalendar=daily
    Persistent=true
    systemctl daemon-reload
    systemctl restart etc-sync.timer
    ls -l /var/lib/systemd/timers/

    A stamp file appeared. Count the completed runs, backdate the stamp as though the machine had been off for three days, and restart the timer.

    journalctl -u etc-sync.service --no-pager | grep -c Finished
    touch -d "3 days ago" /var/lib/systemd/timers/stamp-etc-sync.timer
    systemctl restart etc-sync.timer
    journalctl -u etc-sync.service --no-pager | grep -c Finished
  6. Clean up

    Remove the timer, the service, the script, and the stamp, on both hosts.

    systemctl disable --now etc-sync.timer
    rm -f /etc/systemd/system/etc-sync.timer /etc/systemd/system/etc-sync.service
    rm -f /usr/local/bin/etc_sync.sh /var/lib/systemd/timers/stamp-etc-sync.timer
    systemctl daemon-reload
    ssh workstation 'rm -rf /tmp/etc_from_servera'
    dnf remove -y rsync