Search code examples
pythonloopstimeouttwisted

Best way to execute a function with time increments in Twisted?


Note, this answer here which works as expected.

I had like to execute a function every X seconds and increment by 2 seconds on every successive run.

So for an example, the first time the function should run at 3 seconds, then it should run at 5, then it should run at 7 seconds and so on...

First run - 3 seconds
Second run - 5 seconds
Third run - 7 seconds
and so on...

My code is

from twisted.internet import task, reactor

timeout = 3 # three seconds

def doWork():
    #do work here
    pass

l = task.LoopingCall(doWork)
l.start(timeout) # call every three seconds

reactor.run()

Solution

  • You could use reactor.callLater(n, fn, ...)

    from twisted.internet import reactor
    
    class Worker:
    
        max_timeout = 11
        increment = 2
    
        def __call__(self, interval):
            interval += self.increment          # <-- increment interval
            if interval > self.max_timeout:
                interval = self.max_timeout     # <-- don't go over max
    
            print(f"do work...{interval} interval")
    
            # call the func after N seconds
            reactor.callLater(interval, self, interval)
    
    def main():
        worker = Worker()
        reactor.callLater(3, worker, 3)         # <-- start in 3 seconds
        reactor.run()
    
    main()
    

    If there comes a point in the code where you need to stop, then simply have logic that doesn't call reactor.callLater().