温馨提示×

ubuntu python如何定时任务

小樊
49
2026-09-04 13:58:35
栏目: 编程语言

在 Ubuntu 上用 Python 做定时任务,常见有几种方式,从简单到专业依次如下:


一、最常用:cron + Python 脚本(推荐)

1️⃣ 写好 Python 脚本

# /home/user/test.py
print("hello cron")

赋予执行权限:

chmod +x /home/user/test.py

2️⃣ 编辑 cron 任务

crontab -e

添加一行(示例:每分钟执行):

* * * * * /usr/bin/python3 /home/user/test.py >> /home/user/cron.log 2>&1

3️⃣ 常用时间格式

* * * * *  命令
分 时 日 月 周

示例:

  • 每天 3 点:
0 3 * * * python3 /home/user/test.py
  • 每 10 分钟:
*/10 * * * * python3 /home/user/test.py

✅ 优点:稳定、系统级、服务器重启仍生效
❌ 缺点:不适合秒级任务


二、Python 内部定时: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 复杂


四、Systemd Timer(Ubuntu 官方推荐方式)

适合服务级定时任务

1️⃣ 创建 service

sudo nano /etc/systemd/system/mytask.service
[Unit]
Description=My Python Task

[Service]
ExecStart=/usr/bin/python3 /home/user/test.py

2️⃣ 创建 timer

sudo nano /etc/systemd/system/mytask.timer
[Unit]
Description=Run mytask daily

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

3️⃣ 启用

sudo systemctl enable mytask.timer
sudo systemctl start mytask.timer

查看:

systemctl list-timers

✅ 最专业、可管理、可日志
❌ 配置稍复杂


五、如何选择?

场景 推荐方式
简单脚本定时 cron
Python 常驻程序 schedule
复杂调度 APScheduler
系统级服务 systemd timer

如果你愿意,可以告诉我:

  • 服务器还是桌面
  • 多久执行一次
  • 是否 需要开机自启

我可以帮你写完整配置。

0