温馨提示×

debian怎么配python定时任务

小樊
33
2026-09-20 11:26:14
栏目: 编程语言

在 Debian 上配置 Python 定时任务,常见有 3 种方式,从最推荐到进阶依次是:


一、使用 cron(最常用 ✅)

1️⃣ 编辑当前用户的定时任务

crontab -e

如果是第一次用,会让你选编辑器(推荐 nanovim)。


2️⃣ 添加 Python 定时任务

示例:每天 3 点执行

0 3 * * * /usr/bin/python3 /home/user/script.py >> /home/user/log.txt 2>&1

参数说明:

分 时 日 月 周   命令
0  3  *  *  *   每天3:00

常用时间写法:

  • 每 5 分钟:*/5 * * * *
  • 每小时:0 * * * *
  • 每周一 4 点:0 4 * * 1

3️⃣ 确认 Python 路径

which python3

4️⃣ 查看任务

crontab -l

5️⃣ 常见问题

✅ 脚本里用绝对路径(cron 没有环境变量)
✅ 日志一定要重定向,否则出错看不到
✅ 虚拟环境要写全:

0 3 * * * /home/user/venv/bin/python /home/user/script.py

二、使用 systemd timer(更现代 ✅✅)

适合服务级任务。

1️⃣ 创建 service

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

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

2️⃣ 创建 timer

sudo nano /etc/systemd/system/mytask.timer
[Unit]
Description=Run Python Task Daily

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

[Install]
WantedBy=timers.target

3️⃣ 启用

sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer

4️⃣ 查看状态

systemctl list-timers

三、Python 内部定时(不推荐生产)

如使用 schedule / APScheduler

import schedule
import time

def job():
    print("run")

schedule.every().day.at("03:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

⚠️ 需要常驻进程,服务器重启要自己管理。


✅ 推荐方案总结

场景 推荐
简单脚本 cron
服务/失败重试 systemd timer
短期测试 Python 内部

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

  • Debian 版本
  • 是不是 root
  • 是否用虚拟环境

我可以直接帮你写一份可用配置。

0