您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Linux下Python定时执行脚本怎么写
在Linux系统中,我们经常需要定时执行Python脚本完成自动化任务。本文将详细介绍5种主流实现方式,并附上具体代码示例。
## 一、使用Crontab定时任务
Crontab是Linux系统最经典的定时任务工具,通过编辑crontab文件即可实现。
### 1. 基本使用方法
```bash
# 编辑当前用户的crontab
crontab -e
# 查看现有任务
crontab -l
# 每天凌晨3点执行
0 3 * * * /usr/bin/python3 /path/to/script.py
# 每30分钟执行一次
*/30 * * * * /usr/bin/python3 /path/to/script.py
# 每周一9:30执行
30 9 * * 1 /usr/bin/python3 /path/to/script.py
当脚本依赖特定环境时,建议: 1. 使用绝对路径 2. 在脚本中激活虚拟环境
* * * * * source /path/to/venv/bin/activate && python /path/to/script.py
Systemd提供了更现代的定时任务管理方式。
/etc/systemd/system/myscript.service
:
[Unit]
Description=My Python Script
[Service]
Type=simple
ExecStart=/usr/bin/python3 /path/to/script.py
/etc/systemd/system/myscript.timer
:
[Unit]
Description=Run myscript daily
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable myscript.timer
sudo systemctl start myscript.timer
import schedule
import time
def job():
print("执行任务...")
# 每10分钟执行
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=30)
def timed_job():
print('每30分钟执行一次')
sched.start()
适合分布式场景的任务调度。
from celery import Celery
from celery.schedules import crontab
app = Celery('tasks', broker='pyamqp://guest@localhost//')
@app.task
def my_task():
print("执行Celery任务")
app.conf.beat_schedule = {
'every-monday-morning': {
'task': 'tasks.my_task',
'schedule': crontab(hour=7, minute=30, day_of_week=1),
},
}
适合复杂任务依赖的场景。
from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
def my_python_script():
print("执行Python脚本")
dag = DAG('my_dag', schedule_interval='0 3 * * *', start_date=datetime(2023, 1, 1))
task = PythonOperator(
task_id='run_script',
python_callable=my_python_script,
dag=dag
)
方案 | 适用场景 | 优点 | 缺点 |
---|---|---|---|
Crontab | 简单定时任务 | 系统原生支持 | 环境变量处理复杂 |
Systemd | 需要系统集成的服务 | 与系统服务深度整合 | 配置较复杂 |
Schedule | 纯Python环境 | 无需系统权限 | 需要常驻进程 |
Celery | 分布式任务 | 支持任务队列 | 需要额外组件 |
Airflow | 复杂工作流 | 可视化任务依赖 | 系统资源占用较大 |
选择建议: - 简单脚本直接使用crontab - 系统服务推荐systemd timer - 需要复杂调度逻辑使用APScheduler - 分布式环境选择Celery - 数据管道类任务用Airflow
通过合理选择定时任务方案,可以大大提高Linux系统下Python自动化任务的可靠性。建议从简单方案开始,随着需求复杂度的提升逐步升级解决方案。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。