在 Twisted 中以时间增量执行函数的最佳方法?
Best way to execute a function with time increments in Twisted?
请注意,此答案 here 符合预期。
我想每 X 秒执行一个函数,并在每个连续的 运行 上增加 2 秒。
举个例子,函数第一次应该 运行 在 3 秒,然后它应该 运行 在 5,然后它应该 运行 在 7 秒等等...
第一个 运行 - 3 秒
秒 运行 - 5 秒
第三个 运行 - 7 秒
等等...
我的密码是
from twisted.internet import task, reactor
timeout = 3 # three seconds
def doWork():
#do work here
pass
l = task.LoopingCall(doWork)
l.start(timeout) # call every three seconds
reactor.run()
你可以使用 reactor.callLater(n, fn, ...)
from twisted.internet import reactor
class Worker:
max_timeout = 11
increment = 2
def __call__(self, interval):
interval += self.increment # <-- increment interval
if interval > self.max_timeout:
interval = self.max_timeout # <-- don't go over max
print(f"do work...{interval} interval")
# call the func after N seconds
reactor.callLater(interval, self, interval)
def main():
worker = Worker()
reactor.callLater(3, worker, 3) # <-- start in 3 seconds
reactor.run()
main()
如果代码中有一个点需要停止,那么只需使用不调用 reactor.callLater()
.
的逻辑即可
请注意,此答案 here 符合预期。
我想每 X 秒执行一个函数,并在每个连续的 运行 上增加 2 秒。
举个例子,函数第一次应该 运行 在 3 秒,然后它应该 运行 在 5,然后它应该 运行 在 7 秒等等...
第一个 运行 - 3 秒
秒 运行 - 5 秒
第三个 运行 - 7 秒
等等...
我的密码是
from twisted.internet import task, reactor
timeout = 3 # three seconds
def doWork():
#do work here
pass
l = task.LoopingCall(doWork)
l.start(timeout) # call every three seconds
reactor.run()
你可以使用 reactor.callLater(n, fn, ...)
from twisted.internet import reactor
class Worker:
max_timeout = 11
increment = 2
def __call__(self, interval):
interval += self.increment # <-- increment interval
if interval > self.max_timeout:
interval = self.max_timeout # <-- don't go over max
print(f"do work...{interval} interval")
# call the func after N seconds
reactor.callLater(interval, self, interval)
def main():
worker = Worker()
reactor.callLater(3, worker, 3) # <-- start in 3 seconds
reactor.run()
main()
如果代码中有一个点需要停止,那么只需使用不调用 reactor.callLater()
.