cron # 最常用,周期性执行任务
systemd timer # 更现代,适合服务级定时任务
at # 只执行一次的定时任务
1. cron:周期性定时任务
cron 是一套定时任务系统。
你看到这些都属于 cron:
crontab -e
crontab -l
sudo crontab -e
/etc/crontab
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
典型写法:
* * * * * /bin/bash /usr/local/scripts/test.sh
例如:
0 2 * * * /bin/bash /usr/local/scripts/backup.sh
意思是:每天凌晨 2 点执行 backup.sh。
所以这种格式:
分 时 日 月 周 命令
就是 cron 格式。
2. systemd timer:systemd 的定时任务
systemd timer 是 systemd 提供的定时器机制。
它不是写在 crontab -e 里,而是写两个文件:
xxx.service
xxx.timer
例如:
/etc/systemd/system/backup.service
/etc/systemd/system/backup.timer
backup.service:定义要执行什么任务。
[Unit]
Description=Backup job
[Service]
Type=oneshot
ExecStart=/bin/bash /usr/local/scripts/backup.sh
backup.timer:定义什么时候执行。
[Unit]
Description=Run backup every day
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
启动 timer:
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
查看 timer:
systemctl list-timers
所以看到这些命令,一般就是 systemd timer:
systemctl list-timers
systemctl status xxx.timer
systemctl enable --now xxx.timer
3. at:一次性定时任务
at 只执行一次,不是周期性。
例如:
echo "touch /tmp/test.txt" | at now + 10 minutes
意思是:10 分钟后执行一次。
查看一次性任务:
atq
删除一次性任务:
atrm 任务编号
分类表
| 类型 | 用途 | 配置位置 / 命令 | 是否周期执行 |
|---|---|---|---|
| cron | 最常用的周期任务 | crontab -e、/etc/crontab、/etc/cron.daily/ |
是 |
| systemd timer | 服务级定时任务 | xxx.service + xxx.timer |
是,也可以一次 |
| at | 一次性任务 | at、atq、atrm |
否,只执行一次 |
最简单理解
cron = 写一行时间表达式,周期执行命令
systemd timer = 写 service + timer 两个配置文件,交给 systemd 管理
at = 指定未来某个时间,只执行一次
你刚开始学 Ubuntu 定时任务,重点掌握这个就行:
crontab -e
然后写:
0 2 * * * /bin/bash /usr/local/scripts/backup.sh >> /var/log/backup.log 2>&1
这个就是典型的 cron 定时任务。