Python:继续方法调用保留,直到配置了延迟时间

时间:2019-04-16 19:07:37

标签: python multithreading timer delay

我的班级从不同的线程/接口开始上班,我的班级必须在配置的延迟时间内处理工作。

def getJob(job):

    work = self._getNextWorkToRun(job)
    if work is None:
        return {}
    #proceed to do work

job通过不同的包发送到此类。我只想每五分钟调用一次_getNextWorkToRun()方法。但是工作每秒钟/少于几秒钟就来了。因此,我必须等到5分钟后才能通过新工作再次致电_getNextWorkToRun()。每个作业都有参考(JOB1,JOB2等),所有作业必须延迟5分钟才能完成。

实现此目标的最佳方法是什么。

1 个答案:

答案 0 :(得分:0)

下面是一个使用线程的示例,作业将随时从任何其他函数添加到作业队列中,并且get_job()函数将连续运行以监视作业并以固定的间隔对其进行处理,直到获得停止标志为止

from threading import Thread
from queue import Queue
import time
from random import random

jobs = Queue()  # queue safely used between threads to pass jobs
run_flag = True

def job_feeder():
    for i in range(10):
        # adding a job to jobs queue, job could be anything, here we just add a string for simplicity
        jobs.put(f'job-{i}')  
        print(f'adding job-{i}')
        time.sleep(random())  # simulate adding jobs randomly
    print('job_feeder() finished')

def get_job():
    while run_flag:
        if jobs.qsize():  # check if there is any jobs in queue first
            job = jobs.get()  # getting the job
            print(f'executing {job}')
        time.sleep(3)
    print('get_job finished')

t1 = Thread(target=job_feeder)
t2 = Thread(target=get_job)

t1.start()
t2.start()

# we can make get_job() thread quit anytime by setting run_flag
time.sleep(20)
run_flag = False

# waiting for threads to quit
t1.join()
t2.join()

print('all clear')

输出:

adding job-0
executing job-0
adding job-1
adding job-2
adding job-3
adding job-4
adding job-5
adding job-6
adding job-7
executing job-1
adding job-8
adding job-9
job_feeder() finished
executing job-2
executing job-3
executing job-4
executing job-5
executing job-6
get_job finished
all clear

请注意get_job()仅处理6个作业,因为我们在20秒后发送退出信号