Ubuntu 定时器管理指南(Systemd 与 Cron 对比)
Ubuntu 系统中主要有两种定时器管理工具:Systemd Timers(现代默认方案,适用于 Ubuntu 16.04 及以上版本)和 Cron(传统方案,兼容性好)。以下分别介绍其管理方法:
Systemd Timers 是 Systemd 提供的时间驱动任务调度工具,相比 Cron 更灵活(支持毫秒级精度、依赖管理),且与系统服务深度集成。
服务单元文件(.service)用于指定定时任务要执行的命令或脚本。
sudo 创建文件(如 mytask.service):sudo nano /etc/systemd/system/mytask.service
/path/to/your/script.sh 为实际脚本路径):[Unit]
Description=My Custom Timer Task # 任务描述
[Service]
Type=simple # 简单类型(适用于大多数脚本)
ExecStart=/path/to/your/script.sh # 要执行的命令(需绝对路径)
Ctrl+X → Y → Enter)。定时器单元文件(.timer)用于设置任务的触发时间(如每天 8 点、每小时第 30 分钟)。
mytask.timer):sudo nano /etc/systemd/system/mytask.timer
Persistent=true 表示系统重启后会补做错过的任务):[Unit]
Description=Run My Task Daily at 8 AM # 定时器描述
[Timer]
OnCalendar=*-*-* 08:00:00 # 触发时间(cron 语法)
Persistent=true # 开机补做
[Install]
WantedBy=timers.target # 依赖 timers.target(系统定时器服务)
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
sudo systemctl status mytask.timer
| 命令 | 作用 |
|---|---|
sudo systemctl list-timers |
列出所有活动的定时器 |
sudo systemctl start mytask.timer |
手动启动定时器 |
sudo systemctl stop mytask.timer |
手动停止定时器 |
sudo systemctl disable mytask.timer |
禁用开机自启动 |
journalctl -u mytask.timer |
查看定时器日志(排查问题) |
Cron 是 Ubuntu 自带的经典定时任务工具,适合简单的周期性任务(如每天备份、每小时清理日志)。
| 命令 | 作用 | 示例 |
|---|---|---|
crontab -e |
编辑当前用户的 crontab 文件 | crontab -e(选择编辑器,如 nano) |
crontab -l |
查看当前用户的定时任务 | crontab -l(显示所有任务) |
crontab -r |
删除当前用户的所有定时任务 | 慎用! 会清空所有任务 |
crontab -ir |
删除前提示确认 | crontab -ir(避免误删) |
sudo crontab -u username -e |
编辑指定用户的任务(需 root) | sudo crontab -u root -e(root 用户任务) |
Cron 任务的每一行包含 6 个字段(前 5 个是时间,最后 1 个是命令):
* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └─── 星期几(0-7,0 和 7 均表示周日)
│ │ │ └───── 月份(1-12)
│ │ └─────── 日期(1-31)
│ └───────── 小时(0-23)
└─────────── 分钟(0-59)
*:任意值(如 * * * * * 表示每分钟执行);*/n:每 n 个单位(如 */5 * * * * 表示每 5 分钟执行);,:分隔多个值(如 0,15,30,45 * * * * 表示每 15 分钟执行);-:范围(如 0 9-17 * * * 表示每天 9 点到 17 点整点执行)。0 2 * * * /home/user/backup.sh
*/30 * * * * rm -rf /tmp/*
30 8 * * 1 /usr/bin/mail -s "Weekly Report" admin@example.com < /var/log/system.log
chmod +x /path/to/script.sh);/usr/bin/ls 而非 ls);0 2 * * * /home/user/backup.sh >> /home/user/backup.log 2>&1
(>> 追加输出,2>&1 将错误输出合并到标准输出);/etc/crontab,格式需指定用户:* * * * * root /usr/bin/apt update # 每分钟以 root 身份执行 apt update(示例)
通过以上方法,你可以高效管理 Ubuntu 系统中的定时任务,根据需求选择合适的工具即可。