在 Ubuntu 中,“定时器”通常有两种常见含义,下面分别说明管理方式:
Ubuntu 16.04 以后默认使用 systemd,可以用 .timer 单元来管理定时任务,功能类似 cron,但更强大。
.service:要执行的任务.timer:控制什么时候执行sudo mkdir -p /etc/systemd/system
编辑 service 文件:
sudo nano /etc/systemd/system/mytask.service
内容:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/bin/echo "hello"
编辑 timer 文件:
sudo nano /etc/systemd/system/mytask.timer
内容:
[Unit]
Description=Run My Task Daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
常用命令:
systemctl list-timers # 查看所有定时器
systemctl status mytask.timer # 查看状态
systemctl stop mytask.timer # 停止
systemctl start mytask.timer # 启动
systemctl disable mytask.timer # 取消开机启动
适合简单的周期性任务。
crontab -e
示例(每天 2 点执行):
0 2 * * * /path/to/script.sh
crontab -l # 查看
crontab -r # 删除
/etc/crontab
/etc/cron.d/
适合“几分钟后执行一次”。
sudo apt install at
echo "shutdown -h now" | at now + 10 minutes
查看:
atq
删除:
atrm 任务号
如果你有具体使用场景(比如“每天备份”“开机运行”“失败重试”),我可以帮你写完整配置。