在 Ubuntu 里“定时器”通常指 systemd timer(服务器/后台任务)或 cron(传统定时任务)。下面分别说明。
sudo vim /etc/systemd/system/mytask.service
内容示例:
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/bin/bash /opt/mytask.sh
sudo vim /etc/systemd/system/mytask.timer
示例(每天 3:00 执行):
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=*-*-* 03: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
crontab -e
示例:
0 3 * * * /opt/mytask.sh
含义:
分 时 日 月 周
0 3 * * *
*/5 * * * * command # 每5分钟
0 0 * * * command # 每天0点
0 9 * * 1 command # 每周一9点
crontab -l
sudo apt install at
echo "/opt/mytask.sh" | at 03:00
如果你有具体执行时间或脚本内容,我可以帮你直接写完整配置。