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
-
Confirm the service still works
Become
rootand run the unit from the previous exercise once by hand.sudo -i systemctl start etc-sync.service systemctl is-failed etc-sync.service -
Write a timer for it
A timer takes the name of the service it triggers, with a
.timersuffix. 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.targetsystemctl daemon-reload -
Enable the timer, not the service
systemctl enable --now etc-sync.timer systemctl list-timers etc-sync.timer --no-pagerNEXTis when it fires next, andACTIVATESnames the service it will start. -
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-pagerLASTandPASSEDnow show a real run. -
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.timerSearch with
/OnCalendar, replace that line with C, then o to open a line below it:OnCalendar=daily Persistent=truesystemctl 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 -
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