BlockingScheduler与BackgroundScheduler区别

编程

BlockingScheduler demo

# coding:utf-8

import time

from apscheduler.schedulers.background import BackgroundScheduler

from apscheduler.schedulers.blocking import BlockingScheduler

# from apscheduler.scheduler import Scheduler

import datetime

def func():

now = datetime.datetime.now()

ts = now.strftime("%Y-%m-%d %H:%M:%S")

print("do func time = ", ts)

def func2():

# 耗时2S

now = datetime.datetime.now()

ts = now.strftime("%Y-%m-%d %H:%M:%S")

print("do func2 time = ", ts)

time.sleep(2)

def dojob():

# 创建调度器:BlockingScheduler

scheduler = BlockingScheduler()

# 添加任务,时间间隔2S

scheduler.add_job(func, "interval", seconds=2, id="test_job1")

# 添加任务,时间间隔5S

scheduler.add_job(func2, "interval", seconds=3, id="test_job2")

scheduler.start()

if __name__ == "__main__":

dojob()

运行结果如下:

("do func  time = ", "2020-02-24 11:35:48")

("do func2 time = ", "2020-02-24 11:35:49")

("do func time = ", "2020-02-24 11:35:50")

("do func time = ", "2020-02-24 11:35:52")

("do func2 time = ", "2020-02-24 11:35:52")

("do func time = ", "2020-02-24 11:35:54")

("do func2 time = ", "2020-02-24 11:35:55")

("do func time = ", "2020-02-24 11:35:56")

...

from apscheduler.schedulers.background import BackgroundScheduler

import time

def job():

print("job 3s")

if __name__=="__main__":

sched = BackgroundScheduler(timezone="MST")

sched.add_job(job, "interval", id="3_second_job", seconds=3)

sched.start()

while(True):

print("main 1s")

time.sleep(1)

job 3s

main 1s

main 1s

main 1s

job 3s

main 1s

main 1s

main 1s

总结

看具体的使用场景来决定使用哪一个,比如,只是用来做定时调度,主进程没有其他需要执行的程序,则使用阻塞的BlockingScheduler ,如果需要在主进程执行其他逻辑,则使用BackgroundScheduler

参考

https://blog.51cto.com/huangyg/2367088

https://blog.csdn.net/ybdesire/article/details/82228840

以上是 BlockingScheduler与BackgroundScheduler区别 的全部内容, 来源链接: utcz.com/z/513782.html

回到顶部