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>In general <code>reactor.callLater()</code> is the function you want. So if the function needs to be called 5 seconds later, your code would look like this:</p>

<pre><code>from twisted.internet import reactor
reactor.callLater(5, cancelTest)
</code></pre>

<p>One thing that is strange is that your <code>task.deferLater</code> implementation should also work. However without seeing more of your code I don't think I can help you more other than stating that it's strange :)</p>

<h1>References</h1>

<ul>
<li><a href="https://twistedmatrix.com/documents/current/core/howto/defer.html#callbacks" rel="nofollow">https://twistedmatrix.com/documents/current/core/howto/defer.html#callbacks</a>
<a href="http://twistedmatrix.com/documents/current/api/twisted.internet.base.ReactorBase.html#callLater" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.internet.base.ReactorBase.html#callLater</a></li>
</ul>

python twisted