how to call a callback function after certain amount of time
<p>I'm using Twisted along with Txmongo lib.
In the following function, I want to invoke cancelTest() 5 secs later. But the code does not work. How can I make it work?</p>

<pre><code>from twisted.internet import task

def diverge(self, d):
    if d == 'Wait':
        self.flag = 1
        # self.timeInit = time.time()
        clock = task.Clock()
        for ip in self.ips:
            if self.factory.dictQueue.get(ip) is not None:
                self.factory.dictQueue[ip].append(self)
            else:
                self.factory.dictQueue[ip] = deque([self])
                # self.factory.dictQueue[ip].append(self)

        log.msg("-----------------the queue after wait")
        log.msg(self.factory.dictQueue)
###############################HERE, this does not work
        self.dtime = task.deferLater(clock, 5, self.printData)
#############################
        self.dtime.addCallback(self.cancelTest)
        self.dtime.addErrback(log.err)
    else:
        self.cancelTimeOut()
        d.addCallback(self.dispatch)
        d.addErrback(log.err)



def sendBackIP(self):
    self.ips.pop(0)
    log.msg("the IPs: %s" % self.ips)

    d = self.factory.service.checkResource(self.ips)

    d.addCallback(self.diverge) ###invoke above function
    log.msg("the result from checkResource: ")
    log.msg()
</code></pre>

<p>you're doing almost everything right; you just didn't get the Clock part correctly.</p>

<p><strong>twisted.internet.task.Clock</strong> is a deterministic implementation of IReactorTime, which is mostly used in unit/integration testing for getting a deterministic output from your code; you shouldn't use that in production.</p>

<p>So, what should you use in production? <strong>reactor</strong>! In fact, all production reactor implementations implement the IReactorTime interface.</p>

<p>Just use the following import and function call:</p>

<pre><code>from twisted.internet import reactor
# (omissis)
self.dtime = task.deferLater(reactor, 5, self.printData)
</code></pre>

<p>Just some sidenotes: </p>

<p>in your text above the snippet, you say that you want to invoke cancelTest after five seconds, but in the code you actually invoke printData; of course if printData just prints something, doesn't raise and returns an immediate value, this will cause the cancelTest function to be executed immediately after since it's a chained callcack; <strong>but if you want to actually be 100% sure, you should call cancelTest within deferLater, not printData</strong>.</p>

<p>Also, I don't understand if this is a kind of "timeout"; please be advised that such callback will be triggered in all situations, even if the tests take less than five seconds. If you need a cancelable task, you should use reactor.callLater directly; that will NOT return a deferred you can use, but will let you cancel the scheduled call.</p>

python twisted