0

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()
Sam
  • 350
  • 5
  • 18
  • LoopingCall can't do this. What else have you tried? – Jean-Paul Calderone May 12 '20 at 12:44
  • @Jean-PaulCalderone - Sorry haven't tried other approaches as I am wanting to use Twisted to handle this as I also use Qt5rector and scrapy in my program both of which work on Twisted. Can you give pointers as what other things I should look into ? – Sam May 13 '20 at 07:48

1 Answers1

1

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().

notorious.no
  • 4,919
  • 3
  • 20
  • 34
  • Thank you for taking the time to answer this question, this works as expected. Much obliged. – Sam May 14 '20 at 00:42