在 CentOS 上配置 Python 定时任务,常用方式有两种:crontab(推荐、简单) 和 systemd timer。下面以 crontab 为主讲,附带 systemd 方式。
which python3
例如:
/usr/bin/python3
例如:/root/scripts/test.py
print("hello cron")
crontab -e
格式:
* * * * * 命令
分 时 日 月 周
示例:
# 每天凌晨 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
✅ 建议:
cron 环境很干净,建议:
0 2 * * * /usr/bin/python3 /root/scripts/test.py
或使用虚拟环境:
0 2 * * * /root/venv/bin/python /root/scripts/test.py
tail -f /var/log/cron
/etc/systemd/system/python-task.service
[Unit]
Description=Python Task
[Service]
ExecStart=/usr/bin/python3 /root/scripts/test.py
/etc/systemd/system/python-task.timer
[Unit]
Description=Run Python Task
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable python-task.timer
systemctl start python-task.timer
查看:
systemctl list-timers
✅ 简单任务 → crontab
✅ 复杂 / 系统级 → systemd timer
如果你愿意,可以告诉我:
我可以帮你写完整配置。