在 CentOS 上配置 Python 定时任务,通常有两种主流方式:cron(推荐,系统级定时) 和 systemd timer。下面分别说明,最常用的是 cron。
crontab -e
如果是 root 用户执行:
sudo crontab -e
* * * * * 命令
分 时 日 月 周
示例:
0 3 * * * /usr/bin/python3 /root/scripts/test.py >> /root/logs/test.log 2>&1
*/5 * * * * /usr/bin/python3 /root/scripts/test.py
✅ 写绝对路径
which python3
输出例如:
/usr/bin/python3
✅ 脚本里不要依赖当前目录
import os
os.chdir("/root/scripts")
✅ 日志一定要重定向
>> /root/logs/test.log 2>&1
crontab -l # 查看任务
systemctl status crond
CentOS 7+:
systemctl restart crond
systemctl enable crond
/opt/mytask.py
vim /etc/systemd/system/mytask.service
[Unit]
Description=Python Task
[Service]
ExecStart=/usr/bin/python3 /opt/mytask.py
vim /etc/systemd/system/mytask.timer
[Unit]
Description=Run Python Task Daily
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now mytask.timer
systemctl list-timers
❌ cron 不执行?
tail -f /var/log/cron
❌ 虚拟环境?
0 3 * * * /root/venv/bin/python /root/scripts/test.py
如果你愿意,可以告诉我:
我可以直接帮你写完整配置。