Linux & Servers

systemd for Pragmatists: Long-Running Services and Timers Instead of cron

Turn your programs and scripts into systemd services that come back after reboots and crashes, log cleanly, and replace cron with timers.

systemd for Pragmatists: Long-Running Services and Timers Instead of cron
Table of contents
  1. A simple service
  2. Logs with journalctl
  3. Hardening in a few lines
  4. Timers: the modern replacement for cron
  5. Quick troubleshooting

If you still run programs with nohup or inside screen, the first reboot or crash will show you why that doesn’t last. systemd is on practically every modern distribution, and a ten-line file gives you automatic start at boot, restart after a crash and centralised logging. The same tool, through “timers”, also replaces cron.

A simple service

Say you have a Python API in /opt/myapi. First create a system user with no login shell, so the program doesn’t run as root:

sudo useradd --system --home /opt/myapi --shell /usr/sbin/nologin myapi
sudo chown -R myapi:myapi /opt/myapi

Then create /etc/systemd/system/myapi.service:

[Unit]
Description=My API service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=myapi
Group=myapi
WorkingDirectory=/opt/myapi
EnvironmentFile=/opt/myapi/.env
ExecStart=/opt/myapi/venv/bin/python -m myapi
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now myapi
systemctl status myapi

enable turns the service on for future boots and --now also starts it right away. Every time you edit a unit file, don’t forget daemon-reload; otherwise systemd keeps using the old version.

A few options worth knowing

Option What it does
Restart=on-failure Restart only if the program exits with an error. always brings it back even after a clean exit.
StartLimitIntervalSec and StartLimitBurst In the [Unit] section. If the program crashes several times in a short window, systemd stops trying (default: 5 times in 10 seconds).
MemoryMax=512M A memory cap; if the program wants more, only this service is killed, not some random other process on the server.
Environment= and EnvironmentFile= Set environment variables without touching the code.

Logs with journalctl

journalctl -u myapi -f                  # follow live
journalctl -u myapi -n 100 --no-pager   # last 100 lines
journalctl -u myapi --since "1 hour ago"
journalctl -u myapi -p err -b           # errors only, current boot

Everything the program writes to stdout and stderr goes to the journal; you don’t need a separate log file and logrotate for it. If the journal grows too large, set SystemMaxUse=500M in /etc/systemd/journald.conf.

Hardening in a few lines

systemd can restrict what a service can reach on the rest of the system. Add these lines to the [Service] section:

NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/myapi/data

With ProtectSystem=strict the whole filesystem is read-only for the service, except the paths listed in ReadWritePaths. systemd-analyze security myapi gives the service an “exposure” score and lists options you could still add.

Don’t edit packaged unit files To change services installed by packages (nginx or docker, for example) use sudo systemctl edit nginx. It creates an override file in /etc/systemd/system/nginx.service.d/ that survives package updates.

Timers: the modern replacement for cron

A scheduled job in systemd consists of two files: a oneshot service that does the work, and a timer that says when to run it. For example, for the backup script from our MariaDB backup guide:

# /etc/systemd/system/db-backup.service
[Unit]
Description=Nightly database backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/db-backup.sh
# /etc/systemd/system/db-backup.timer
[Unit]
Description=Run db-backup every night

[Timer]
OnCalendar=*-*-* 03:30:00
RandomizedDelaySec=10m
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now db-backup.timer
systemctl list-timers db-backup.timer
sudo systemctl start db-backup.service    # one manual run to test

Note: you enable the timer, not the service. The service only runs when the timer triggers it.

Why timers beat cron

  • Jobs aren’t skipped: with Persistent=true, if the server was off at 03:30 the job runs after it boots; cron silently skips it.
  • No overlapping runs: if the previous run hasn’t finished, systemd won’t start a second copy alongside it.
  • Logs and status: each run’s output is in journalctl -u db-backup, and systemctl status db-backup tells you whether the last run succeeded.
  • Resource limits and hardening: every option from the previous section works for scheduled jobs too.

To write a schedule expression, systemd-analyze calendar is your friend: give it an expression and it shows the next run time:

systemd-analyze calendar "Mon..Fri 09:00"
systemd-analyze calendar "*-*-01 04:00:00"   # first day of every month
systemd-analyze calendar "*:0/15"            # every 15 minutes

Quick troubleshooting

  • systemd-analyze verify /etc/systemd/system/myapi.service reports syntax errors in the file.
  • If the service fails with status=203/EXEC, the ExecStart path is wrong or the file isn’t executable. Always use full paths in ExecStart.
  • status=217/USER means the user named in User= doesn’t exist.
  • If the program exits right after starting and systemd keeps restarting it, journalctl -u myapi -n 50 almost always shows why.

About the author

Sina Farahmand

DevOps and back-end developer, into automation, CI/CD and command-line tools. If he has to do something twice, he writes a script for it.

All articles by Sina Farahmand

Comments

No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.

Leave a comment