Python:如何更改此代码,以便每60秒执行一次doWork()?

时间:2012-05-20 10:29:45

标签: python twisted

如何更改此代码,以便每隔60秒调用一次doWork()。目前,它正在循环,并在60秒后停止。想要完全相反。

from twisted.internet import task
from twisted.internet import reactor
import twapi
timeout = 200.0 # Sixty seconds

def doWork():
    #do work here
    twapi.main('1')
    pass

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

2 个答案:

答案 0 :(得分:5)

来自oficial Twisted documentation

from twisted.internet import task
from twisted.internet import reactor

def runEverySecond():
    print "a second has passed"

l = task.LoopingCall(runEverySecond)
l.start(1.0) # call every second

reactor.run()

答案 1 :(得分:0)

我修改了你的脚本,以便在一分钟内输出当前时间:

#!/usr/bin/python
from twisted.internet import task
from twisted.internet import reactor
from datetime import datetime as time
timeout = 60.0 # Sixty seconds

def doWork():
    #do work here
    print time.now().isoformat()

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

它就像那样:

2012-05-20T19:24:44.388682
2012-05-20T19:25:44.389788
2012-05-20T19:26:44.389424

我可以看到你的代码片段中唯一的问题是你要求反应堆每200秒调用一次你的函数,而不是60.