Python Forum
Stopping scheduler with condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stopping scheduler with condition
#1
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
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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.
Reply
#4
Alright than! You can use a decorator to provide the delay, the counter and the condition values for any code execution.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
See http://python-forum.io/Thread-Multi-trhe...imer-Class

I moved this over from a post I put on the old forum
Reply
#6
@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
Reply
#7
Thought I fixed that. Yes, there is!

fixed just now
Reply
#8
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.
Reply
#9
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.
Reply
#10
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Running Python script through Task Scheduler? Winfried 8 335 Mar-10-2024, 07:24 PM
Last Post: Winfried
  stopping number conversion before end Skaperen 6 2,942 Jul-12-2020, 09:22 AM
Last Post: DeaD_EyE
  Stopping a loop in another file catosp 4 2,599 Jun-15-2020, 02:45 PM
Last Post: catosp
  else condition not called when if condition is false Sandz1286 10 5,739 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 7,704 Jun-01-2020, 06:00 PM
Last Post: penahuse
  how to cancel scheduler module event nanok66 0 2,097 May-11-2020, 10:31 PM
Last Post: nanok66
  Getting an .exe to run from Task Scheduler fioranosnake 2 2,974 Dec-06-2019, 12:20 PM
Last Post: DeaD_EyE
  Simple mutli-threaded scheduler using sched - stuck Mzarour 2 6,050 Nov-12-2019, 07:44 PM
Last Post: Mzarour
  Batch file not running python script in task scheduler davork 3 4,478 May-09-2019, 12:53 PM
Last Post: Gribouillis
  Help with Stopping a function after a timer SheeppOSU 0 1,913 Jan-28-2019, 10:13 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020