简体   繁体   English

替代threading.timer python

[英]Alternative for threading.timer python

I am trying to implement a timer for calling the function for printing the queue after specific time .I am also able to cancel the timer if the queue gets filled before that specified time and print the queue.But after that my timer object behaves abruptly causing timers to overlap for example if the queue gets filled in 2 sec then it prints the queue in 2,8,2,8... time interval instead of 2,10 time interval 我正在尝试实现一个计时器,以在特定时间后调用用于打印队列的函数。如果在指定时间之前队列已满,我也可以取消计时器并打印队列。但是在那之后,我的计时器对象的行为突然导致计时器重叠,例如,如果队列在2秒内被填满,则它以2,8,2,8 ...时间间隔而不是2,10时间间隔打印队列

connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1'))
channel = connection.channel()
channel.queue_declare(queue='final', durable=True)

global msg_queue
global t

msg_queue=queue.Queue(maxsize=6)

def empty_queue():
    print(time.time())
    l=[]
    i=int(msg_queue.qsize())
    while i!=0:
        l.append(msg_queue.get())
        i-=1
    t=threading.Timer(10,empty_queue)
    print(l)
    t.start()



t=threading.Timer(10,empty_queue)
print(time.time())
t.start()

while True:
    if int(msg_queue.qsize())<6:
        consume_generator = channel.consume(queue='final', no_ack=True)
        result=next(consume_generator)
        msg_queue.put(json.loads(result[2].decode("utf-8")))

    else:
        print("more",time.time())
        t.cancel()
        empty_queue()

I have solved the issue by cancelling the timer to prevent its own duplicacy 我已通过取消计时器来防止重复操作来解决此问题

def empty_queue():
    global t
    print(time.time())
    l=[]
    i=int(msg_queue.qsize())
    while i!=0:
        l.append(msg_queue.get())
        i-=1
    if t.isAlive():
       t.cancel()
    t=threading.Timer(10,empty_queue)
    print(l)
    t.start()

You could nest a if statement inside the timer that says if queue is full then disable this if statement then let the timer continue until its done without affecting the queue. 您可以在计时器内嵌套一条if语句,该语句说如果队列已满,则禁用此if语句,然后让计时器继续运行直至完成,而不会影响队列。 I don't think it will cause conflict with your program because the timer is probably a closure. 我认为这不会与您的程序产生冲突,因为计时器可能是关闭的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM