在 Linux 中,定时启动进程常见有以下几种方式,按使用场景从简单到高级说明:
cron(最常用,适合周期性任务)crontab -e
分 时 日 月 周 命令
30 3 * * * /home/user/backup.sh
*/10 * * * * /usr/bin/python3 /home/user/task.py
0 8 * * 1 /home/user/weekly.sh
crontab -l # 查看
crontab -r # 删除
✅ 适合:定时脚本、备份、清理任务
at(一次性定时任务)sudo apt install at # Debian/Ubuntu
sudo yum install at # CentOS
at 23:00
然后输入:
/home/user/run.sh
按 Ctrl+D 结束
at now + 1 hour
at 2026-01-20 10:00
✅ 适合:只运行一次的定时任务
systemd timer(现代服务器推荐)# /etc/systemd/system/mytask.service
[Unit]
Description=My Task
[Service]
ExecStart=/home/user/mytask.sh
# /etc/systemd/system/mytask.timer
[Unit]
Description=Run My Task Daily
[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now mytask.timer
✅ 适合:系统级服务、需要日志、高可靠性
sleep + nohup(简单但不够规范)nohup bash -c 'sleep 3600 && /home/user/task.sh' &
⚠ 不推荐用于生产环境
| 场景 | 推荐方式 |
|---|---|
| 周期任务 | cron |
| 一次性任务 | at |
| 系统服务 | systemd timer |
| 临时测试 | sleep |
如果你有具体需求(例如:每隔 5 分钟、开机自启、带参数、容器环境),可以告诉我,我可以给你精确示例。