Scheduling a task to be run in the future

Let's say you want to run a task X seconds in the future. The way to do that is defined in the reactor interface twisted.internet.interfaces.IReactorTime:

from twisted.internet import reactor

def f(s):
    print "this will run in 3.5 seconds: %s" % s

reactor.callLater(3.5, f, "hello, world")



If we want a task to run every X seconds repeatedly, we can just re-add it every time it's run:

from twisted.internet import reactor

def runEverySecond():
    print "a second has passed"
    reactor.callLater(1, runEverySecond)

reactor.callLater(1, runEverySecond)



Spreading tasks over time

Note: Delayeds may be deprecated in the future.

Sometimes we want to schedule tasks to be run at intervals, e.g. a long calculation that might block twisted if the whole thing were to be run at once. We do this using objects that conform to the Delayed interface (see twisted.python.delay).

A delayed must define two functions:

For example:
class LongCalculation:
    """Runs at least 100 multipications a minute."""
    
    value = 1L
    
    def timeout(self):
        return 0.01
    
    def runUntilCurrent(self):
       self.value = self.value * 2L

# register the Delayed object with the Twisted event loop:
o = LongCalculation()
from twisted.internet import main
main.addDelayed(o)