Ubuntu系统除Crontab外定时执行Python脚本的可行方案有哪些?
可行解决方案汇总
方案1:基于现有Crontab做轻量改造(无需替换工具)
- 给每个脚本加固定/随机延迟启动,直接修改crontab命令即可打散一分钟内的启动峰值,避免同时启动带来的负载冲高。该方案天然满足单个脚本失败不影响其他的要求,所有命令都是独立启动、无依赖。
- 固定延迟配置示例,10个脚本每间隔6秒启动一个:
* * * * * python3 /home/ubuntu/script1/script1.py * * * * * sleep 6 && python3 /home/ubuntu/script2/script2.py * * * * * sleep 12 && python3 /home/ubuntu/script3/script3.py ...
- 随机延迟配置示例,每个脚本每分钟启动时随机等待0-59秒执行:
* * * * * python3 /home/ubuntu/script1/script1.py * * * * * sleep $((RANDOM\%60)) && python3 /home/ubuntu/script2/script2.py * * * * * sleep $((RANDOM\%60)) && python3 /home/ubuntu/script3/script3.py ...
方案2:使用systemd timer替代Crontab
- systemd timer原生支持秒级精度的定时配置,可给每个脚本单独配置service和timer单元,各个任务的启动时间、资源限制、重启策略完全隔离,单个脚本执行出错、崩溃完全不会影响其他任务,还支持统一查看所有定时任务的执行状态、运行日志。
- 单任务配置示例:
- 创建service配置
/etc/systemd/system/script1.service:
[Unit] Description=Run script1定时任务 [Service] User=ubuntu ExecStart=python3 /home/ubuntu/script1/script1.py- 创建对应timer配置
/etc/systemd/system/script1.timer,可自定义每分钟的具体执行秒数来错开峰值:
[Unit] Description=script1任务的定时器 [Timer] OnCalendar=*-*-* *:*:00 AccuracySec=1s Persistent=true [Install] WantedBy=timers.target- 执行命令生效配置:
systemctl daemon-reload systemctl enable --now script1.timer - 创建service配置
- 所有定时任务状态可通过
systemctl list-timers统一查询。
方案3:使用轻量自定义调度器
- 若后续还会新增大量同类脚本,可使用Python的
APScheduler库写一个统一的调度主脚本,给每个子脚本设置不同的执行偏移时间,同时内置异常捕获逻辑,单个子脚本执行错误只会记录日志、不会中断调度器也不会影响其他任务。 - 核心逻辑示例:
from apscheduler.schedulers.blocking import BlockingScheduler import subprocess import logging logging.basicConfig(level=logging.INFO) def run_script(script_path): try: # 超时设置避免脚本僵死占用资源 subprocess.run(["python3", script_path], check=True, capture_output=True, timeout=30) logging.info(f"{script_path} 执行成功") except Exception as e: logging.error(f"{script_path} 执行失败: {str(e)}") if __name__ == "__main__": sched = BlockingScheduler(timezone="Asia/Shanghai") # 每个任务设置不同的执行秒数,错开启动峰值 sched.add_job(run_script, 'cron', minute='*', second=0, args=["/home/ubuntu/script1/script1.py"]) sched.add_job(run_script, 'cron', minute='*', second=6, args=["/home/ubuntu/script2/script2.py"]) sched.add_job(run_script, 'cron', minute='*', second=12, args=["/home/ubuntu/script3/script3.py"]) # 依次添加剩余脚本即可 sched.start()
- 调度主脚本可配置为systemd服务实现开机自启、异常自动重启。
内容的提问来源于stack exchange,提问作者SSC Fan
相关产品推荐
相关产品推荐

