用twisted为未来安排任务(Scheduling tasks for the future

我们想再x秒后执行一个任务,可以使用twisted.internet.interfaces.IReactorTime:

  1. from twisted.internet import reactor
  2. def f(s):
  3.     print "this will run 3.5 seconds after it was scheduled: %s" % s
  4. reactor.callLater(3.5, f, "hello, world")


如果想每x秒就重复执行一个任务,可以使用twisted.internet.task.LoopingCall:

  1. from twisted.internet import task
  2. def runEverySecond():
  3.     print "a second has passed"
  4. l = task.LoopingCall(runEverySecond)
  5. l.start(1.0) # call every second
  6. # l.stop() will stop the looping calls


如果想要取消一个已经安排的任务:

  1. from twisted.internet import reactor
  2. def f():
  3.     print "I'll never run."
  4. callID = reactor.callLater(5, f)
  5. callID.cancel()

 

翻译 -- Jerry Marx.

你可能感兴趣的:(future)