<?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Scheduling tasks for the future</title> </head> <body> <h1>Scheduling tasks for the future</h1> <p>Let's say we want to run a task X seconds in the future. The way to do that is defined in the reactor interface <code class="API">twisted.internet.interfaces.IReactorTime</code>:</p> <pre class="python"> from twisted.internet import reactor def f(s): print "this will run 3.5 seconds after it was scheduled: %s" % s reactor.callLater(3.5, f, "hello, world") </pre> <p>If we want a task to run every X seconds repeatedly, we can use <code class="API">twisted.internet.task.LoopingCall</code>:</p> <pre class="python"> from twisted.internet import task def runEverySecond(): print "a second has passed" l = task.LoopingCall(runEverySecond) l.start(1.0) # call every second # l.stop() will stop the looping calls </pre> <p>If we want to cancel a task that we've scheduled:</p> <pre class="python"> from twisted.internet import reactor def f(): print "I'll never run." callID = reactor.callLater(5, f) callID.cancel() </pre> </body> </html>