Python定时任务4种实现方式
1、Thread定时执行
Python中,利用标准库threading中的Timer类可以轻松创建定时任务。
1.1 使用 threading.Timer 实现
import threading
def hello():
print("Hello, Python")
# 创建定时器 ,5秒后执行hello函数
t = threading.Timer(5.0, hello)
t.start() # 开始计时
1.2 定时任务管理与取消策略
在应用中,可能需要根据条件动态管理定时任务,比如取消尚未执行的任务。threading.Timer对象提供了cancel()方法来取消尚未启动的任务:
import threading
import time
def hello():
print("Hello,Pyhton")
t = threading.Timer(5.0, hello)
t.start() # 开始计时
time.sleep(5)
if t.is_alive(): # 检查定时器是否还在运行
t.cancel()
print("定时器还在运行")
else:
print("定时器不还在运行")
2、Schedule库定时执行
schedule库是一个Python定时任务库
2.1 安装与基本用法
pip install schedule -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
import schedule
import time
def hello():
print("Hello,Pyhton")
# 每隔10秒执行一次hello函数
schedule.every(10).seconds.do(hello)
while True:
schedule.run_pending()
time.sleep(1)
这段代码会持续运行,每10秒输出一次指定的信息 ,直到手动中断。
2.2 高级功能:重复任务与异常处理
schedule库支持灵活的时间间隔设置,除了基本的秒、分钟、小时等单位外 ,还可以设定特定日期和时间执行任务,或者按周、月重复执行。
每日特定时间执行:
schedule.every().day.at("10:30").do(hello)
每周一早上9点执行:
schedule.every().monday.at("09:00").do(hello)
异常处理
在长时间运行的定时任务中 ,异常处理很重要。可以通过try-except结构来捕获并适当处理任务执行过程中可能出现的错误 ,确保定时任务框架的稳定运行。
import schedule
import time
def hello():
try:
print(a)
except Exception as e:
print(f"error:{e}")
# 每隔5秒执行一次hello函数
schedule.every(5).seconds.do(hello)
while True:
schedule.run_pending()
time.sleep(1)
在这个示例,即使hello内部的代码发生异常 ,程序也不会直接崩溃 ,而是会捕获异常并打印错误信息 ,然后继续等待下一个执行周期。
3. APScheduler框架
APScheduler 是一个功能全面且高度可定制的定时任务库。
pip install apscheduler -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
def hello():
print("当前时间是" + str(datetime.datetime.now()))
scheduler = BlockingScheduler()
scheduler.add_job(hello, 'interval', seconds=5)
scheduler.start()
这段代码会每隔5秒执行一次hello函数,打印当前时间。
3.2 不同类型的触发器介绍
• IntervalTrigger:用于在固定时间间隔后重复执行任务。例如,每隔5秒执行一次。
from apscheduler.schedulers.blocking import BlockingScheduler scheduler = BlockingScheduler() scheduler.add_job(hello, 'interval', seconds=5)
• CronTrigger:类似于Linux的cron,支持复杂的周期性计划,如每天凌晨1点执行。
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
import datetime
def hello():
print("当前时间是" + str(datetime.datetime.now()))
trigger = CronTrigger(hour=1, minute=0) # 每天凌晨1点执行
scheduler = BlockingScheduler()
scheduler.add_job(hello, trigger)
• DateTrigger:在特定的日期和时间只执行一次。
from apscheduler.triggers.date import DateTrigger
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
def hello():
print("当前时间是" + str(datetime.datetime.now()))
trigger = DateTrigger(run_date=datetime.datetime(2025, 12, 1)) # 在2025年12月1日执行
scheduler = BlockingScheduler()
scheduler.add_job(hello, trigger)
4.使用asyncio实现异步定时
Python中,asyncio是一个用于编写并发代码的库,利用协程(coroutine)、事件循环(event loop)和任务(task)等 ,实现了异步IO操作。协程是一种轻量级的子例程,可以在等待IO操作(如网络请求、磁盘读写)期间挂起,从而使其他任务得以执行,提高了程序的效率和响应速度。
asyncio实现定时执行案例
import asyncio
async def print_every_three_seconds():
while True:
print("测试测试")
await asyncio.sleep(3)
async def main():
# 创建一个任务并启动
task = asyncio.create_task(print_every_three_seconds())
# 保持主程序运行,否则事件循环一旦执行完就会结束
await asyncio.sleep(10) # 让主程序等待10秒后自然结束
asyncio.run(main())

浙公网安备 33010602011771号