在 Ubuntu 上用 Python 做定时任务,常见有几种方式,从简单到专业依次如下:
cron + Python 脚本(推荐)# /home/user/test.py
print("hello cron")
赋予执行权限:
chmod +x /home/user/test.py
crontab -e
添加一行(示例:每分钟执行):
* * * * * /usr/bin/python3 /home/user/test.py >> /home/user/cron.log 2>&1
* * * * * 命令
分 时 日 月 周
示例:
0 3 * * * python3 /home/user/test.py
*/10 * * * * python3 /home/user/test.py
✅ 优点:稳定、系统级、服务器重启仍生效
❌ 缺点:不适合秒级任务
schedule 库(适合常驻程序)pip install schedule
import schedule
import time
def job():
print("定时任务执行")
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
运行:
python3 test.py
✅ 简单直观
❌ 程序不能退出,需后台运行
APScheduler适合复杂任务(定时、间隔、日期)
pip install apscheduler
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print("APScheduler 任务")
sched = BlockingScheduler()
sched.add_job(job, 'interval', seconds=30)
sched.start()
✅ 功能强大
❌ 比 cron 复杂
适合服务级定时任务
sudo nano /etc/systemd/system/mytask.service
[Unit]
Description=My Python Task
[Service]
ExecStart=/usr/bin/python3 /home/user/test.py
sudo nano /etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask daily
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable mytask.timer
sudo systemctl start mytask.timer
查看:
systemctl list-timers
✅ 最专业、可管理、可日志
❌ 配置稍复杂
| 场景 | 推荐方式 |
|---|---|
| 简单脚本定时 | cron |
| Python 常驻程序 | schedule |
| 复杂调度 | APScheduler |
| 系统级服务 | systemd timer |
如果你愿意,可以告诉我:
我可以帮你写完整配置。