python time模块定时器由浅入深应用实例
作者:傻子的尴尬 IT智慧谷
Python提供了多种实现定时任务的方法,从简单到复杂,包括使用标准库time模块的基础定时,threading或asyncio模块的多线程/异步定时,以及第三方库如APScheduler的高级定时任务调度
引言
在Python中,定时器是一个非常实用的功能,它可以帮助我们在特定时间后执行某段代码。这在许多应用场景中都极为重要,例如数据抓取的定时任务、定期发送邮件提醒、系统监控等。
下面将逐步介绍几种Python定时器的实现方式及其应用场景。
1. 简单定时器(time.sleep())
import time
def simple_timer():
print("开始计时...")
time.sleep(5) # 暂停5秒
print("5秒钟已过...")
simple_timer()2. 基于threading模块的定时器
import threading
import time
def timer_function(name):
def function():
print(f"{name} 定时器启动,等待3秒...")
time.sleep(3)
print(f"{name} 定时器结束.")
return function
# 创建并启动定时器
timer1 = threading.Timer(0, timer_function("Timer1"))
timer2 = threading.Timer(2, timer_function("Timer2"))
timer1.start()
timer2.start()
# 主线程等待所有定时器结束
while threading.active_count() > 1:
time.sleep(1)3. 使用asyncio模块实现异步定时器
import asyncio
async def timer coroutine(seconds):
print(f"开始计时,等待{seconds}秒...")
await asyncio.sleep(seconds)
print(f"{seconds}秒钟已过...")
async def main():
task1 = asyncio.create_task(timer_coroutine(3))
task2 = asyncio.create_task(timer_coroutine(5))
await task1
await task2
asyncio.run(main())4. 高级定时任务调度库APScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print("定时任务触发:现在是 %s" % datetime.now())
scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', minutes=1)
scheduler.start()5. 使用schedule第三方库(简单易用,适合定时任务调度)
import schedule
import time
def job():
print("定时任务触发:现在是 %s" % datetime.now())
# 每天凌晨3点执行job函数
schedule.every().day.at("03:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)6. 使用concurrent.futures模块结合threading.Timer实现多线程定时任务管理
import concurrent.futures
import threading
import time
def timer_function(name, seconds):
def function():
print(f"{name} 定时器启动,等待{seconds}秒...")
time.sleep(seconds)
print(f"{name} 定时器结束.")
return function
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future1 = executor.submit(threading.Timer(0, timer_function("Timer1", 3)).start)
future2 = executor.submit(threading.Timer(2, timer_function("Timer2", 5)).start)
concurrent.futures.wait([future1, future2])总结
以上就是从简单到复杂的Python定时器实现方式及其应用场景。根据实际需求和项目规模,你可以选择适合自己的定时器方案。简单的定时可以通过time.sleep()完成,对于更复杂的定时任务,可以利用Python的多线程或多进程能力,或者利用异步IO来提高程序效率。而当需要进行复杂的定时任务调度时,诸如APScheduler这样的第三方库则能提供强大且灵活的解决方案。
以上就是python time模块定时器由浅入深应用实例的详细内容,更多关于python time定时器模块的资料请关注脚本之家其它相关文章!
