Ubuntu定时器使用教程:Systemd与Cron两种方法
Systemd是Ubuntu的初始化系统,其内置的systemd-timers子系统提供了精准、灵活的定时任务管理功能,支持依赖管理、日志集成等特性。
服务单元文件用于指定定时任务要执行的命令或脚本。
sudo权限创建服务文件(以mytask.service为例):sudo nano /etc/systemd/system/mytask.service/path/to/your/script.sh替换为实际脚本路径):[Unit]
Description=My Custom Timer Service # 任务描述
[Service]
ExecStart=/path/to/your/script.sh # 要执行的命令(需绝对路径)
nano按Ctrl+O保存,Ctrl+X退出)。定时器单元文件用于设置任务的执行时间,支持OnCalendar(日历时间)、OnBootSec(开机后延迟)等多种触发方式。
mytask.timer):sudo nano /etc/systemd/system/mytask.timerOnCalendar格式):[Unit]
Description=Run My Task Daily at 8:00 AM # 定时器描述
[Timer]
OnCalendar=*-*-* 08:00:00 # 每天8点触发(格式:年-月-日 时:分:秒)
Persistent=true # 若错过触发时间,下次启动时立即执行
[Install]
WantedBy=timers.target # 关联到timers.target(系统定时器服务)
sudo systemctl daemon-reloadsudo systemctl enable mytask.timersudo systemctl start mytask.timersudo systemctl status mytask.timer使用journalctl命令查看定时任务的执行日志(替换mytask.service为你的服务名):
sudo journalctl -u mytask.service -f
(-f表示实时跟踪日志,-u指定服务单元)
OnCalendar示例*/5 * * * *0 3 * * *0 9 * * 10 12 1 * *0 18 * * 1-5Cron是Linux系统的经典定时任务工具,通过crontab命令管理,适合简单的周期性任务。
sudo apt update && sudo apt install cronsudo systemctl start cronsudo systemctl enable cronnano):crontab -e分钟 小时 日 月 星期 命令),例如:# 每分钟将当前时间写入日志文件
* * * * * date >> /home/username/time.log
# 每天凌晨2点执行备份脚本
0 2 * * * /home/username/backup.sh >> /home/username/backup.log 2>&1
(>>表示追加输出,2>&1将错误输出重定向到标准输出)crontab -lcrontab -rsudo crontab -u username -echmod +x /path/to/script.sh)。PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin)。>> /path/to/logfile.log 2>&1),便于排查问题。通过以上教程,你可以根据需求选择合适的方法,在Ubuntu上轻松创建和管理定时任务。