最小的 service

[Unit]
Description=my app
After=network-online.target

[Service]
Type=simple
User=app
WorkingDirectory=/srv/app
ExecStart=/srv/app/run.sh
Restart=on-failure
RestartSec=3

[Install]
WantedBy=multi-user.target

放到 /etc/systemd/system/app.service,然后:

systemctl daemon-reload
systemctl enable --now app

定时任务

.service 加 .timer 两个文件,比 cron 好在能查历史。

[Unit]
Description=nightly job

[Service]
Type=oneshot
ExecStart=/usr/local/bin/nightly
[Unit]
Description=run nightly job

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

[Install]
WantedBy=timers.target

常看的命令

systemctl status app --no-pager
journalctl -u app -n 50 --no-pager
journalctl -u app --since "1 hour ago"
systemctl list-timers --all

文件改了要重载

daemon-reload 只重读单元文件,不会重启服务;改完记得 restart。