本文目录导读:

我来详细介绍几种常用的脚本定时执行任务的方法。
Linux/macOS:Crontab(最常用)
基本用法
# 编辑定时任务 crontab -e # 查看当前用户的定时任务 crontab -l # 删除所有定时任务 crontab -r
Crontab 格式
* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └── 星期 (0-7, 0和7都表示周日)
│ │ │ └──── 月份 (1-12)
│ │ └────── 日期 (1-31)
│ └──────── 小时 (0-23)
└────────── 分钟 (0-59)
示例
# 每天凌晨2点执行备份脚本 0 2 * * * /home/user/backup.sh # 每5分钟执行一次监控脚本 */5 * * * * /path/to/monitor.sh # 工作日(周一到周五)早9点执行 0 9 * * 1-5 /path/to/work_task.sh # 每月1号和15号执行 0 0 1,15 * * /path/monthly_task.sh # 每小时执行一次 0 * * * * /path/hourly_task.sh
Windows:任务计划程序
使用 PowerShell 创建计划任务
# 创建每天执行的任务 $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\scripts\task.ps1" $trigger = New-ScheduledTaskTrigger -Daily -At "09:00AM" $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount Register-ScheduledTask -TaskName "MyDailyTask" -Action $action -Trigger $trigger -Principal $principal # 使用 schtasks 命令 schtasks /create /tn "MyTask" /tr "C:\scripts\backup.bat" /sc daily /st 02:00
常用 schtasks 参数
# 每天执行 schtasks /create /tn "TaskName" /tr "program.exe" /sc daily /st 09:00 # 每周执行(周一) schtasks /create /tn "TaskName" /tr "script.bat" /sc weekly /d MON /st 10:00 # 系统启动时执行 schtasks /create /tn "TaskName" /tr "script.bat" /sc onstart # 每小时执行 schtasks /create /tn "TaskName" /tr "script.bat" /sc hourly
Shell 脚本实现定时执行
使用 sleep 循环(简单但占用进程)
#!/bin/bash
# 每10分钟执行一次循环
while true; do
/path/to/your/script.sh
sleep 600 # 等待10分钟
done
更优雅的 at 命令(一次性任务)
# 在指定时间执行一次 echo "/path/to/script.sh" | at 14:30 # 明天下午3点执行 echo "backup.sh" | at 3pm tomorrow # 5小时后执行 echo "cleanup.sh" | at now + 5 hours
Docker 中使用 cron
Dockerfile 配置
FROM ubuntu:latest # 安装 cron RUN apt-get update && apt-get install -y cron # 添加定时任务 ADD crontab /etc/cron.d/my-cron-job RUN chmod 0644 /etc/cron.d/my-cron-job # 启动 cron CMD ["cron", "-f"]
对应 crontab 文件
# 每30分钟执行一次
*/30 * * * * /usr/local/bin/my-script.sh
Python 脚本方案
使用 schedule 库
import schedule
import time
def job():
print("执行任务...")
# 每10分钟执行
schedule.every(10).minutes.do(job)
# 每天上午9:30执行
schedule.every().day.at("09:30").do(job)
# 每周一执行
schedule.every().monday.do(job)
# 每小时执行
schedule.every().hour.do(job)
while True:
schedule.run_pending()
time.sleep(1)
使用 APScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
def my_task():
print("定时任务执行了")
scheduler = BlockingScheduler()
scheduler.add_job(my_task, 'interval', minutes=30) # 每30分钟
scheduler.add_job(my_task, 'cron', hour=2) # 每天凌晨2点
scheduler.start()
最佳实践建议
日志和调试
# crontab 输出重定向 */5 * * * * /path/script.sh >> /var/log/mytask.log 2>&1 # 发送邮件报告 0 2 * * * /path/backup.sh | mail -s "备份结果" admin@example.com
环境变量问题
# crontab 中设置 PATH PATH=/usr/local/bin:/usr/bin:/bin # 或使用绝对路径 0 2 * * * /usr/bin/python3 /home/user/script.py
使用 systemd timers(现代 Linux)
# /etc/systemd/system/my-task.service [Service] ExecStart=/usr/local/bin/my-script.sh Type=simple # /etc/systemd/system/my-task.timer [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target
调试技巧
# 检查 cron 是否运行 systemctl status cron # 测试 cron 表达式 */5 * * * * /bin/echo "测试" >> /tmp/test.log # 查看 cron 日志 tail -f /var/log/syslog | grep CRON
注意事项
- 权限问题:确保执行脚本具有相应权限
- 路径问题:使用绝对路径避免歧义
- 环境变量:cron 运行在有限环境中
- 资源监控:避免同时运行过多任务
- 错误处理:添加完善的错误处理逻辑
选择哪种方案取决于你的操作系统需求和项目环境,对于简单任务推荐 crontab,复杂场景可以考虑 Python 或 systemd timer。