定时任务调度
Python数据分析入门Python
问题
如何设置Python脚本定时执行?
答题要点
# 方法1:schedule库(简单场景)
import schedule
import time
def daily_report():
# 执行报表生成逻辑
print("生成日报...")
# ...
# 每天9点执行
schedule.every().day.at("09:00").do(daily_report)
# 每小时执行
schedule.every().hour.do(daily_report)
# 每周一执行
schedule.every().monday.at("10:00").do(daily_report)
while True:
schedule.run_pending()
time.sleep(60)
# 方法2:APScheduler(生产环境推荐)
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', hour=9, minute=0)
def daily_report():
print("生成日报...")
@scheduler.scheduled_job('interval', hours=1)
def hourly_check():
print("每小时检查...")
scheduler.start()
# 方法3:Linux crontab(运维部署)
# 0 9 * * * /usr/bin/python3 /path/to/report.py
# 方法4:Airflow(企业级调度平台)
from airflow import DAG
from airflow.operators.python import PythonOperator
dag = DAG('daily_report', schedule_interval='0 9 * * *')
task = PythonOperator(task_id='generate_report', python_callable=daily_report, dag=dag)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题