Mastering Systemd Services and Timers: A Complete Guide
Introduction to Systemd
Systemd is the modern init system for Linux, providing powerful service management capabilities and dependency handling.
Creating Systemd Services
Basic Service Unit
[Unit]
Description=My Custom Service
After=network.target
[Service]
ExecStart=/usr/bin/myscript.sh
Restart=always
User=serviceuser
Group=servicegroup
[Install]
WantedBy=multi-user.target
Advanced Features
- Environment variables:
Environment="DB_HOST=localhost"
Environment="DB_PORT=5432"
- Resource limits:
LimitNOFILE=65535
LimitNPROC=4096
Systemd Timers
Creating Timers
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=daily
Persistent=true
Unit=backup.service
[Install]
WantedBy=timers.target
Advanced Timer Options
- Randomized delay:
RandomizedDelaySec=1h
- Accuracy control:
AccuracySec=1min
Troubleshooting and Debugging
- Check service status:
systemctl status myservice
- View logs:
journalctl -u myservice
- Dependency analysis:
systemd-analyze critical-chain myservice
Performance Optimization
- Parallel startup:
DefaultDependencies=no
- Service isolation:
ProtectSystem=full
PrivateTmp=true
Conclusion
Systemd provides robust service management capabilities that are essential for modern Linux system administration.