在 Ubuntu 中,有多種方法可以設置定時任務。以下是一些常用的定時器命令和工具:
cron:
crontab: 用于編輯用戶的定時任務。crontab -e
crontab -l: 列出當前用戶的定時任務。crontab -r: 刪除當前用戶的定時任務。Cron 的時間格式為:分 時 日 月 星期,例如 0 0 * * * /path/to/command 表示每天午夜執行命令。
systemd timers:
systemctl: 用于管理 systemd 定時器。systemctl list-timers
systemctl start mytimer.timer
systemctl stop mytimer.timer
systemctl enable mytimer.timer
systemctl disable mytimer.timer
/etc/systemd/system/ 目錄下。at:
at: 用于一次性定時任務。
at now + 1 minute
然后在提示符下輸入要執行的命令,完成后按 Ctrl+D。
查看待處理任務:
atq
刪除待處理任務:
atrm <job_number>
這些工具各有優缺點,選擇適合的工具取決于具體需求。對于常規的周期性任務,cron 是最常用的選擇;而對于需要更復雜調度或與 systemd 集成的任務,systemd timers 可能更合適。