Python Forum
Stopping scheduler with condition - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Stopping scheduler with condition (/thread-1303.html)

Pages: 1 2


Stopping scheduler with condition - j.crater - Dec-22-2016

Hello,
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 scheduler
The 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


RE: Stopping scheduler with condition - wavic - Dec-22-2016

Hello! I didn't look at your code but the simplest way is just to use time.sleep(delay). It suspends execution of the code for a certain amount of time. Time can be a float type.

import time

while #condition:
    # code execution
    # condition change
    time.sleep(1)
Or you can use a for loop to execute the code specific number of times with if statement in it to check for a condition

for i in range(counter):
    if condition:
        #execute the code
         time.sleep(1)
    else:
        break



RE: Stopping scheduler with condition - j.crater - Dec-22-2016

Ah, I forgot to include an important detail in my original post, sorry about that...

The code to be executed at each scheduled time has unknown and variable execution time. That's why I didn't go with time.sleep() in the first place. That would not allow constant time intervals between executions. Thank you.


RE: Stopping scheduler with condition - wavic - Dec-22-2016

Alright than! You can use a decorator to provide the delay, the counter and the condition values for any code execution.


RE: Stopping scheduler with condition - Larz60+ - Dec-22-2016

See http://python-forum.io/Thread-Multi-trheaded-Timer-Class

I moved this over from a post I put on the old forum


RE: Stopping scheduler with condition - j.crater - Jan-03-2017

@wavic I am not yet familiar with decorators. I trust you it is a good solution, but I am simply not there yet =)

@Larz60+ Thank you for your code using threading module. With some online searching, I have already found similar solutions, but I always had a problem with stopping the timer in a graceful enough way. I have to investigate further. By the way, is there a typo... multiplier = [86400, 36000, 60, 1], specifically with 36000 having a spare '0'? In "function3()" print says "'Function 2 triggered'. There is also: "These startement shows". Another comment, nowadays you would probably rephrase "for n in range(len(times))". Sorry for being a pain, but I would expect/want others to chew my code in same way! :D

I found this answer on Stack Overflow, it might resolve my issue:
http://stackoverflow.com/a/11083919


RE: Stopping scheduler with condition - Larz60+ - Jan-03-2017

Thought I fixed that. Yes, there is!

fixed just now


RE: Stopping scheduler with condition - j.crater - Jan-03-2017

I ran the provided code exactly as it is. Functions (fun1, fun2, fun3, finalone) get executed at the time, provided as an argument to addEvent.
How do you recommend me to modify the code, so a function gets executed repeatedly with a fixed interval, not just once?
It would stop executing after a certain condition is met.

I see there is a count variable within addEvent function, but altering it has no effect.
Correction, it has effect, just not expected one. It delays function execution.


RE: Stopping scheduler with condition - Larz60+ - Jan-03-2017

I wrote this quite some time back
Not sure it's a great solution, just thought I'd 'throw an iron in the fire'.
It was copied over from post I made in the old forum.
The original date was Feb 2015, I had only been using python for a year.


RE: Stopping scheduler with condition - j.crater - Jan-03-2017

I understand that. I like the idea of the code you wrote, that is why I am trying to make the most of it. And along the way give feedback and hopefully suggest improvements too.