Using systemd timer

Systemd timer can be used to replace Cron for job scheduler. A timer file must be accompanied by a service file with the same name by default (except for the suffix). The service is triggered when the timer elapses. Because Omarine 6.0 does not use dcron, I write this article to guide you to create your own timer if needed.
We begin with a timer updating virus database that has been set up in Omarine 6.0. That is the pair of timer file clamav-freshclam.timer and service file clamav-freshclam.service.

File /lib/systemd/system/clamav-freshclam.timer:

[Unit]
Description=ClamAV virus database updater

[Timer]
OnCalendar=02,14:10:00
Persistent=true

[Install]
WantedBy=timers.target

In the [Timer] section, OnCalendar=02,14:10:00 defines that the timer will trigger the service at 02:10 and 14:10 daily. With Persistent=true, the last triggered time is stored on disk, and the service will be triggered immediately if at least one triggering event is lost while the machine is off. This ensures the reasonability of the event over time. See systemd.timer(5) and systemd.time(7) for more options.

File /lib/systemd/system/clamav-freshclam.service:

[Unit]
Description=ClamAV virus database updater
DefaultDependencies=no
After=rc-local.service
Before=shutdown.target

[Service]
ExecStart=/usr/bin/freshclam
Restart=on-failure
RestartSec=30s
SuccessExitStatus=0 1

SuccessExitStatus=0 1 ensure that when the virus database is up-to-date, the process returns 1 will be considered successful.

Note: DO NOT set RemainAfterExit=yes in any timer service files because the service will not be restarted when the timer elapses.

You can schedule a virus scan of your /home directory automatically at 3 AM daily by making a timer called clamdscan as follows, as the root user:

cat > /lib/systemd/system/clamdscan.timer << EOF
[Unit]
Description=ClamAV virus scan

[Timer]
OnCalendar=03:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF

cat > /lib/systemd/system/clamdscan.service << EOF
[Unit]
Description=ClamAV virus scan
Requires=clamav-daemon.service
After=clamav-daemon.service

[Service]
ExecStart=/usr/bin/clamdscan /home
EOF

Then you start clamav-daemon service and the timer:

sudo systemctl enable clamav-daemon   &&
sudo systemctl start clamav-daemon    &&
sudo systemctl enable clamdscan.timer &&
sudo systemctl start clamdscan.timer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.