在 Debian(以及大多数使用 systemd 的现代 Linux 发行版)中,“定时器”通常指 systemd timer(比传统的 cron 更灵活)。下面按从入门到常用的方式说明如何启用。
systemctl --version
如果能看到版本信息,说明使用的是 systemd。
systemd 定时器需要两个文件:
sudo nano /etc/systemd/system/hello.service
内容示例:
[Unit]
Description=Hello Task
[Service]
Type=oneshot
ExecStart=/usr/bin/echo "Hello from systemd timer"
实际使用中可换成脚本路径,如
/opt/scripts/backup.sh
sudo nano /etc/systemd/system/hello.timer
内容示例(每天 03:00 执行):
[Unit]
Description=Run hello daily
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=hello.service
[Install]
WantedBy=timers.target
常见时间写法:
OnCalendar=dailyOnCalendar=hourlyOnCalendar=Mon-Fri 09:00:00OnBootSec=5min(开机 5 分钟后)sudo systemctl daemon-reload
sudo systemctl enable --now hello.timer
systemctl list-timers
systemctl status hello.timer
查看下次执行时间:
systemctl list-timers hello.timer
sudo systemctl start hello.service
journalctl -u hello.service
| 特性 | systemd timer | cron |
|---|---|---|
| 日志 | journald | /var/log |
| 精度 | 高 | 中 |
| 依赖控制 | 强 | 弱 |
| 开机错过任务 | 支持 | 不支持 |
crontab -e
示例(每天 3 点):
0 3 * * * /opt/scripts/backup.sh
如果你能告诉我:
我可以给你更精确的配置示例。