#test_time03_pi.py # copied by D@CC on 2021EMay31 # stop by ^C or Stop/Restart Backend # tested ok import asyncio def foo(): #single timed operation # loop.stop() # D@CC this will stop the loop timer. . eventually print("timer went off!") def fooLoopEnd(): # D@CC print("done loop") # D@CC def fooTick(nn): print(nn[0]) def countdown(n): # internal timer loop task; n is the counter of ticks if n[0] == 0: #loop.stop() # end loop.run_forever() ## D@CC commented out the above to make it loop forever loop.call_later(4, foo) # call foo() in 4 seconds #schedule a task ## added above by D@CC to (optionally) repeat foo in every loop fooLoopEnd() # added by D@CC event at end of loop n[0]=10 # added by D@CC to loop forever else: #print(n[0]) # show each tick (D@CC:optional) fooTick(n) #fooTick routine runs once per tick n[0] -= 1 # reduce n each tick def frange(start=0, stop=None, step=1): #internal timer range function while stop is None or start < stop: yield start start += step #NOTE: loss of precision over time def call_every(loop, seconds, func, *args, now=True): #internal timer definition def repeat(now=True, times=frange(loop.time() + seconds, None, seconds)): if now: func(*args) loop.call_at(next(times), repeat) repeat(now=now) loop = asyncio.get_event_loop() #create timer named loop loop.call_later(4, foo) # call foo() in 4 seconds #schedule a task call_every(loop, 0.5, countdown, [10]) # repeat the call every .5 seconds # timerName DTtick(secs) timer-action (timer-init) loop.run_forever() # can stop after 1 loop loop.close() # close the timer print("done") #inform user #end test_timer.py #Source: https://stackoverflow.com/questions/5177439/postponing-functions-in-python/14040516#14040516 #Source: https://docs.python.org/3/library/asyncio.html#:~:text=asyncio%20is%20used%20as%20a,high%2Dlevel%20structured%20network%20code. #Output #10 #9 #8 #7 #6 #5 #4 #3 #timer went off! #2 #1 #done # D@CC stops here if loop.stop() is not commented out # # if no loop.stop ... 10,9,8,7 ..... 3, timer went off, 2, 1, 10, 9 etc #end test_timer03_pi.py #/test_time03_pi.py