温馨提示×

centos如何配python定时

小樊
37
2026-10-23 21:37:01
栏目: 编程语言

在 CentOS 上配置 Python 定时任务,通常有两种主流方式:cron(推荐,系统级定时) 和 systemd timer。下面分别说明,最常用的是 cron。


一、使用 cron 定时执行 Python 脚本(最常用)

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

crontab -e

如果是 root 用户执行:

sudo crontab -e

2. 基本格式

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

示例:

  • 每天 3:00 执行
0 3 * * * /usr/bin/python3 /root/scripts/test.py >> /root/logs/test.log 2>&1
  • 每 5 分钟执行
*/5 * * * * /usr/bin/python3 /root/scripts/test.py

3. 注意事项(很重要)

✅ 写绝对路径

which python3

输出例如:

/usr/bin/python3

✅ 脚本里不要依赖当前目录

import os
os.chdir("/root/scripts")

✅ 日志一定要重定向

>> /root/logs/test.log 2>&1

4. 查看和测试

crontab -l          # 查看任务
systemctl status crond

CentOS 7+:

systemctl restart crond
systemctl enable crond

二、使用 systemd timer(更现代,适合服务化)

1. 编写 Python 脚本

/opt/mytask.py

2. 创建 service

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

[Service]
ExecStart=/usr/bin/python3 /opt/mytask.py

3. 创建 timer

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

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

[Install]
WantedBy=timers.target

4. 启用

systemctl daemon-reload
systemctl enable --now mytask.timer
systemctl list-timers

三、常见问题排查

❌ cron 不执行?

  • 检查 cron 服务是否运行
  • 检查 python 路径
  • 看日志:
tail -f /var/log/cron

❌ 虚拟环境?

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

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

  • CentOS 版本(6 / 7 / 8 / Stream)
  • 是否用虚拟环境
  • 想每天 / 每小时 / 每分钟执行

我可以直接帮你写完整配置。

0 踩