在 Ubuntu 里“定时器”通常有两种常见含义,下面分别说明如何设置周期:
这是 Ubuntu 16.04 以后最标准的方式。
sudo vim /etc/systemd/system/mytask.service
内容示例:
[Unit]
Description=My Task
[Service]
Type=simple
ExecStart=/usr/bin/bash /opt/mytask.sh
sudo vim /etc/systemd/system/mytask.timer
每 10 分钟执行一次
[Unit]
Description=Run mytask every 10 min
[Timer]
OnCalendar=*:0/10
Persistent=true
[Install]
WantedBy=timers.target
每天 3:30 执行
OnCalendar=*-*-* 03:30:00
每周一 02:00
OnCalendar=Mon *-*-* 02:00:00
每小时
OnCalendar=hourly
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
systemctl list-timers
systemctl status mytask.timer
crontab -e
分 时 日 月 星期 命令
每 5 分钟
*/5 * * * * /opt/mytask.sh
每天 2:30
30 2 * * * /opt/mytask.sh
每周日 0 点
0 0 * * 0 /opt/mytask.sh
每 1 小时
0 * * * * /opt/mytask.sh
crontab -l
| 场景 | 推荐 |
|---|---|
| 系统服务、需要日志 | ✅ systemd timer |
| 简单脚本、快速 | ✅ crontab |
| 需要开机自动运行 | 两者都可 |
如果你愿意,可以告诉我:
我可以帮你写一份可直接用的配置。