如何在线程中使用 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
I have a simple example:
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()
it's script not correct work. I want to:
1) print 'test'
2) start 3 threads, waiting while all threads stops
3) sleep 2 seconds
4) repeat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LoopingCall 将每 N 秒运行一次您传递给它的可调用函数,其中 N 是您传递给开始的数字。它不会在上一个调用完成后等待 N 秒,而是在上一个调用开始后等待 N 秒。换句话说,它尝试保持在由 N 和开始时间定义的时间间隔内,在 N 秒、N * 2 秒、N * 3 秒等处运行调用。
如果进程太忙而无法进行以下操作之一调用,它将跳过该迭代。如果调用返回 Deferred,并且 Deferred 在下一个时间间隔内尚未触发,则它将跳过该迭代。
因此,您可以通过在
loop
末尾返回d
来更接近您想要的行为,但LoopingCall
不会总是等待 2延迟触发后几秒。它将等待下一个 N 秒的倍数(从开始时间算起),然后再次调用该函数。LoopingCall
will run the callable you pass to it every N seconds, where N is the number you pass to start. It doesn't wait N seconds after the previous call finishes, it waits N seconds after the previous call started. In other words, it tries to stay on the interval defined by N and the starting time, running a call at N seconds, N * 2 seconds, N * 3 seconds, etc.If the process is too busy for it to make one of the calls, it will skip that iteration. If the call returns a Deferred and the Deferred has not fired by the next interval, it will skip that iteration.
So, you can get closer to your desired behavior by returning
d
at the end ofloop
, butLoopingCall
isn't going to always wait 2 seconds after the Deferred fires. It will wait for the next multiple of N seconds, counting from the start time, and call the function again then.