SYSTEMD

SYSTEM Daemon Starts and monitors system and user services.

Overview

Command Description
systemctl status <serivename>.service Status of service (active, inactive, enabled, disabled, ...)
systemctl list-timers <servicename>.timer Status of service timer (time since last run, next planned start, ...)
/etc/systemd/system/ Directory of self created services

Create timed service

  1. Create service entry
sudo nano /etc/systemd/system/<servicename>.service
[Unit]
Description=<what the service / called script does>
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot|simple
RemainAfterExit=no
User=<user for script>
Group=<group of files?>
Environment=HOME=<home directory>
ExecStart=/usr/bin/flock --nonblock /tmp/<lock filename>.lock <script with absolute path>
ExecStop=
  • wants/after network-online.target mean that this service needs the network to be online
  • Type oneshot is for short running tasks like backup scripts, simple for permanently running things like server and databases
  • additional line RemainAfterExit=yes would be for things like mount which result is active even if the service has exited - then also an additional lne for ExecStop would be necessary to unmount the service
  • flock create lock file to prevent different backups running in parallel
  • nonblock means, that additional starts doesn't wait but stop executing
  1. Test service
sudo systemctl daemon-reload
sudo systemctl start <servicename>.service
sudo systemctl status <servicename>.service
  1. Create timer
sudo nano /etc/system/system/<servicename>.timer
[Unit]
Description=<name and how often as title>

[Timer]
OnCalendar=*-*-* 03:15:00
Persistent=false
Unit=<servicename>.service

[Install]
WantedBy=timers.target
  • OnCalendar sets time for daily start
  • Persistent=true would mean, that if Raspi would be offline during start time, the run will be catched up after the next start
  1. Enable / activate Timer
sudo systemctl daemon-reload
sudo systemctl enable --now <servicetimer>.timer
systemctl status <servicetimer>.timer
  • --now starts the timer after enabling

List all timers

systemctl list-timers or systemctl list-timers <servicename>.timer

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9