scheduler和timer的区别

复制代码

from apscheduler.schedulers.blocking import BlockingScheduler
import time
from threading import Timer
from datetime import datetime

def test1(who):
print("hello")
print(datetime.now())

time.sleep(20)
print("this is %s" %who)
print(datetime.now())
def scheduler_test():
scheduler = BlockingScheduler()

i=0
while i<3:
scheduler.add_job(test1, 'interval', seconds=60, id='test_job'+str(i), args=["xiao"+str(i)],next_run_time=datetime.now())
i=i+1
print("mmmmmmm")
scheduler.start()
def timer1(who):
who_tmp=who
test1(who)
Timer(60, timer1,
kwargs={'who': who_tmp}).start()

def timer_test():
i=0
while i<3:
timer1("xiao"+str(i))
i=i+1


if __name__ == '__main__':
timer_test()
#scheduler_test()
print("when")
 
复制代码

以上面这个demo为例,我们分别得到调用timer和调用scheduler时程序返回的结果

timer

scheduler

 

可以看到 1、 timer的多个定时任务是串行启动起来,而scheduler是并行的,

                2、timer的定时间隔是不把程序执行时间计算在内的,定时间隔是这一轮执行结束的时间到下一轮开始的时间。而scheduler的定时间隔是这一轮启动到下一轮启动的时间

也就是说如果应用场景对启动时间点非常敏感的,那么推荐使用scheduler。

如果使用timer的话,那么每个下一轮的启动时间点都会比上一轮慢一点,此时如果我们要以启动时间点作为横坐标来做数据分析,可能会有带来一些问题

posted on   该用户很懒  阅读(314)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示