python time模块定时器由浅入深应用实例
引言
在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定时器模块的资料请关注脚本之家其它相关文章!
相关文章
Python 在 VSCode 中使用 IPython Kernel 的方法详解
这篇文章主要介绍了Python 在 VSCode 中使用 IPython Kernel 的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-09-09
Python报错TypeError: tuple indices must be
在Python编程过程中,我们经常会遇到各种各样的报错信息,其中,“TypeError: tuple indices must be integers or slices, not str”这个报错,对于很多开发者来说,可能既熟悉又陌生,今天,我们就来深入探讨一下这个报错,看看它是如何产生的,以及如何快速有效地解决它2025-01-01
Python使用wxPython和PyMuPDF实现合并PDF文档
处理大量的PDF文档可能会变得复杂和耗时,但是,使用Python编程和一些强大的库,可以使这个任务变得简单而高效,下面我们就来看看Python如何使用wxPython和PyMuPDF合并PDF文档并自动复制到剪贴板吧2023-11-11
Python实现图片指定位置加图片水印(附Pyinstaller打包exe)
这篇文章主要介绍了Python实现图片指定位置加图片水印,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-03-03


最新评论