Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5106

Python • Re: Change sleep duration of a loop without restarting it (use a variable from an imported script?)

$
0
0
Adjustable loop time is possible, but at some cost of code lines.
Here a sample, needs some more refinement to handle thread safety. But it demonstrates the basics.

Code:

import threadingimport timet0 = time.time()def do_something():    """a small sample for something useful"""    print( f"{time.time()-t0:.1f} do something")class AdjustableLoop:    """loop a target method each loop_time_second       - allows ro adjust the loop time while running       - target is executed in a thread       """    def __init__(self, target, loop_time_second):        self.target = target                self.loop_time_second = loop_time_second        self.changed_wait_time_second = loop_time_second                self.wait = threading.Event()                t0 = threading.Thread(target=self.while_loop, name="adjustableloop")        t0.start()    def while_loop(self):        while True:            # do something useful            self.target()                        # and sleep            wait_is_set = self.wait.wait(timeout = self.loop_time_second)            if wait_is_set:                # wait event is set                self.wait.clear()                # not perfect, as multiple changes can ocurr and it                # does not handle the already expired time in the loop                if self.changed_wait_time_second > self.loop_time_second:                    wait_is_set = self.wait.wait(timeout =                                            self.changed_wait_time_second -                                            self.loop_time_second)            else:                # timeout occurred                pass            self.loop_time_second = self.changed_wait_time_second                def set_loop_time(self, changed_wait_time_second):        print( f"set_loop_time {changed_wait_time_second}")        self.changed_wait_time_second = changed_wait_time_second        self.wait.set()   adjustable_loop = AdjustableLoop(do_something, 7)def change_time():    """change_time is producing some test values"""    # just change times for the loop    while True:        time.sleep(30)        adjustable_loop.set_loop_time( 11)        time.sleep(30)        adjustable_loop.set_loop_time( 13)t1 = threading.Thread(target=change_time)t1.start()keep_running = threading.Event()keep_running.wait()

Statistics: Posted by ghp — Wed Jan 22, 2025 10:20 pm



Viewing all articles
Browse latest Browse all 5106

Trending Articles