I've done this article before (It's actually my most viewed article of all). But here we go again with the updated version.
Systemd Service Files: A Practical Guide
Creating custom systemd services is a common task for Linux administrators. This guide demonstrates service file creation through two examples: a simple time logger and a more complex SSH monitoring service.
Service File Basics
Systemd service files live in /etc/systemd/system/ and consist of three main sections:
[Unit] - Description and dependencies
[Service] - How the service runs
[Install] - When/how to enable it
Example 1: Simple Time Logger
Let's create a service that logs the current time every hour.
The Script:
Make it executable:
The Service File:
The Timer File:
Managing the Service:
Systemd Service Files: A Practical Guide
Creating custom systemd services is a common task for Linux administrators. This guide demonstrates service file creation through two examples: a simple time logger and a more complex SSH monitoring service.
Service File Basics
Systemd service files live in /etc/systemd/system/ and consist of three main sections:
[Unit] - Description and dependencies
[Service] - How the service runs
[Install] - When/how to enable it
Example 1: Simple Time Logger
Let's create a service that logs the current time every hour.
The Script:
Code:
#!/bin/bash
/usr/local/bin/timelog.sh
LOGFILE="/var/log/timelog.log"
echo "(date′+(date '+%Y-%m-%d %H:%M:%S') - Service executed" >> "
(date′+LOGFILE"
Make it executable:
Code:
chmod +x /usr/local/bin/timelog.sh
Code:
/etc/systemd/system/timelog.service
[Unit]
Description=Time Logger Service
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/timelog.sh
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Code:
/etc/systemd/system/timelog.timer
[Unit]
Description=Run Time Logger every hour
Requires=timelog.service
[Timer]
OnBootSec=5min
OnUnitActiveSec=1h
Unit=timelog.service
[Install]
WantedBy=timers.target
Code:
Reload systemd to recognize new files
sudo systemctl daemon-reload
Enable and start the timer
sudo systemctl enable timelog.timer
sudo systemctl start timelog.timer
Check status
sudo systemctl status timelog.timer
sudo systemctl status timelog.service
View logs
sudo journalctl -u timelog.service -f
Stop and disable
sudo systemctl stop timelog.timer
sudo systemctl disable timelog.timer

