如何通过线程使用LoopingCall? [英] How to use LoopingCall with threads?

查看:14
本文介绍了如何通过线程使用LoopingCall?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的例子:

from twisted.internet import utils, reactor
from twisted.internet import defer
from twisted.internet import threads
from twisted.internet.task import LoopingCall,deferLater
import time

def test1():
    print 'test'

def test2(res):
       l = []
       for i in xrange(3):
           l.append(threads.deferToThread(test4))
       return defer.DeferredList(l)

def test3(res):
    pass

def test4():
    print 'thread start'
    time.sleep(10)
    print 'thread stop'


def loop():
    d = defer.maybeDeferred(test1)
    d = d.addCallback(test2)
    d.addCallback(test3)

LoopingCall(loop).start(2)

reactor.run()

这是不正确的剧本。我想:

1) print 'test'
2) start 3 threads, waiting while all threads stops
3) sleep 2 seconds 
4) repeat

推荐答案

LoopingCall将每隔N秒运行您传递给它的Callable,其中N是您传递给Start的编号。它不会在上一次调用结束后等待N秒,而是在上一次调用开始后等待N秒。换句话说,它试图保持在N和开始时间定义的间隔内,以N秒、N*2秒、N*3秒等时间运行呼叫。

如果进程太忙而无法进行其中一个调用,它将跳过该迭代。如果调用返回延迟,并且到下一个时间间隔仍未触发延迟,则它将跳过该迭代。

因此,您可以通过在loop的末尾返回d来更接近您想要的行为,但LoopingCall不会总是在延迟触发后等待2秒。它将等待N秒的下一个倍数,从开始时间开始计数,然后再次调用该函数。

这篇关于如何通过线程使用LoopingCall?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆