Python定时任务4种实现方式

1、Thread定时执行

Python中,利用标准库threading中的Timer类可以轻松创建定时任务。

1.1 使用 threading.Timer 实现

1
2
3
4
5
6
7
8
9
10
import threading
 
 
def hello():
    print("Hello, Python")
 
 
# 创建定时器 ,5秒后执行hello函数
t = threading.Timer(5.0, hello)
t.start()  # 开始计时

  

1.2 定时任务管理与取消策略

在应用中,可能需要根据条件动态管理定时任务,比如取消尚未执行的任务。threading.Timer对象提供了cancel()方法来取消尚未启动的任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 安装与基本用法

1
pip install schedule -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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库支持灵活的时间间隔设置,除了基本的秒、分钟、小时等单位外 ,还可以设定特定日期和时间执行任务,或者按周、月重复执行。

每日特定时间执行:

1
schedule.every().day.at("10:30").do(hello)

每周一早上9点执行:

1
schedule.every().monday.at("09:00").do(hello)

异常处理  

在长时间运行的定时任务中 ,异常处理很重要。可以通过try-except结构来捕获并适当处理任务执行过程中可能出现的错误 ,确保定时任务框架的稳定运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 是一个功能全面且高度可定制的定时任务库。

1
pip install apscheduler -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com

  

1
2
3
4
5
6
7
8
9
10
11
12
13
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秒执行一次。

1
2
3
4
5
from apscheduler.schedulers.blocking import BlockingScheduler
 
scheduler = BlockingScheduler()
 
scheduler.add_job(hello, 'interval', seconds=5)

• CronTrigger:类似于Linux的cron,支持复杂的周期性计划,如每天凌晨1点执行。  

1
2
3
4
5
6
7
8
9
10
11
12
13
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:在特定的日期和时间只执行一次。  

1
2
3
4
5
6
7
8
9
10
11
12
13
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实现定时执行案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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())

 

posted @   北京测试菜鸟  阅读(1104)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2023-10-18 Python Traceback:异常信息定位
点击右上角即可分享
微信分享提示