Hello,
I need to execute some code repeatedly with a fixed interval. I scraped this piece of code online:
My attempt was to add a counter variable inside periodic_event(), make checks (e.g. if cnt < 10), and if condition is satisfied call periodic_scheduler.stop(). But I couldn't make it work with all the scope errors I got. So I believe the approach wasn't a good one and there is probably a more obvious, standard solution, that I am not aware of.
What do you suggest me to do in this case? Did I even take the right direction in achieving the goal (executing a function specific number of times with fixed interval)?
Thank you,
JC
I need to execute some code repeatedly with a fixed interval. I scraped this piece of code online:
class PeriodicScheduler(object): def __init__(self): self.scheduler = sched.scheduler(time.time, time.sleep) def setup(self, interval, action, actionargs=()): action(*actionargs) self.event = self.scheduler.enter(interval, 1, self.setup, (interval, action, actionargs)) def run(self): self.scheduler.run() def stop(self): self._running = False if self.scheduler and self.event: self.scheduler.cancel(self.event) # This is the event to execute every time def periodic_event(): print("hello") # Start the scheduler INTERVAL = 1 periodic_scheduler = PeriodicScheduler() periodic_scheduler.setup(INTERVAL, periodic_event) # it executes the event just once periodic_scheduler.run() # it starts the schedulerThe code works fine, it prints "hello" every second. I must say I never used schedulers before and so far didn't study the shown code deeply, so I don't fully understand how it works. But I would like to modify it so that the scheduled event only executes a given number of times.
My attempt was to add a counter variable inside periodic_event(), make checks (e.g. if cnt < 10), and if condition is satisfied call periodic_scheduler.stop(). But I couldn't make it work with all the scope errors I got. So I believe the approach wasn't a good one and there is probably a more obvious, standard solution, that I am not aware of.
What do you suggest me to do in this case? Did I even take the right direction in achieving the goal (executing a function specific number of times with fixed interval)?
Thank you,
JC