温馨提示×

centos怎么配置python定时

小樊
36
2026-10-09 06:19:10
栏目: 编程语言

在 CentOS 上配置 Python 定时任务,常用方式有两种:crontab(推荐、简单) 和 systemd timer。下面以 crontab 为主讲,附带 systemd 方式。


一、使用 crontab 配置 Python 定时任务(最常用)

1️⃣ 确认 Python 路径

which python3

例如:

/usr/bin/python3

2️⃣ 编写 Python 脚本

例如:/root/scripts/test.py

print("hello cron")

3️⃣ 编辑 crontab

crontab -e

4️⃣ 添加定时任务

格式:

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

示例:

# 每天凌晨 2 点执行
0 2 * * * /usr/bin/python3 /root/scripts/test.py >> /root/scripts/log.txt 2>&1

# 每 5 分钟执行
*/5 * * * * /usr/bin/python3 /root/scripts/test.py

✅ 建议:

  • 使用 绝对路径
  • 重定向日志方便排查

二、常见问题排查

❌ Python 环境变量问题

cron 环境很干净,建议:

0 2 * * * /usr/bin/python3 /root/scripts/test.py

或使用虚拟环境:

0 2 * * * /root/venv/bin/python /root/scripts/test.py

❌ 查看 cron 日志(CentOS 7)

tail -f /var/log/cron

三、使用 systemd timer(更专业)

1️⃣ 创建 service

/etc/systemd/system/python-task.service

[Unit]
Description=Python Task

[Service]
ExecStart=/usr/bin/python3 /root/scripts/test.py

2️⃣ 创建 timer

/etc/systemd/system/python-task.timer

[Unit]
Description=Run Python Task

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

[Install]
WantedBy=timers.target

3️⃣ 启动

systemctl daemon-reload
systemctl enable python-task.timer
systemctl start python-task.timer

查看:

systemctl list-timers

四、总结建议

✅ 简单任务 → crontab
✅ 复杂 / 系统级 → systemd timer

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

  • CentOS 版本(7 / 8 / Stream)
  • Python 版本
  • 想每天 / 每小时 / 什么条件执行

我可以帮你写完整配置。

0 踩