我有一个简单的例子:

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 秒运行一次您传递给它的可调用对象,其中 N 是您传递给它的数字。它不会在上一次调用完成后等待 N 秒,而是在上一次调用开始后等待 N 秒。换句话说,它尝试停留在 N 和开始时间定义的间隔上,在 N 秒、N * 2 秒、N * 3 秒等处运行一次调用。

如果进程太忙而无法进行其中一个调用,它将跳过该迭代。如果调用返回一个 Deferred 并且 Deferred 没有在下一个间隔触发,它将跳过该迭代。

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

关于python - 如何在线程中使用 LoopingCall?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7218108/

10-12 23:17