在Ubuntu中,可通过cron或systemd设置任务执行间隔,具体如下:
crontab -e
,添加如下格式的任务(*
为通配符,/n
表示每隔n单位时间):
*/5 * * * * /path/to/command
30 * * * * /path/to/command
0 3 * * * /path/to/command
sudo service cron restart
(部分系统需用 sudo systemctl restart cron
)。/etc/systemd/system/mytask.service
):[Unit]
Description=My Task
[Service]
ExecStart=/path/to/command
/etc/systemd/system/mytask.timer
):[Unit]
Description=Run My Task every 5 minutes
[Timer]
OnUnitActiveSec=5min # 间隔5分钟执行
Unit=mytask.service
[Install]
WantedBy=timers.target
sudo systemctl enable --now mytask.timer
sudo systemctl list-timers # 查看定时器状态
chmod +x /path/to/command
)。*/n
表示“每隔n单位”,*
表示“任意值”,逗号(,
)和横杠(-
)可用于指定多个时间点。