Skip to content
Snippets Groups Projects
Commit 9fb31ff8 authored by pi's avatar pi
Browse files

add AsyncLoopService

parent 447d5379
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/env python3
"""
demo service to show some AsyncLoop methods
Move this file one dir up to work
"""
import asyncio
from lib.Service import Service
from lib.LoopDecorator import BackoffTimerException, backoff_timer
class AsyncLoopExamples(Service):
def __init__(self) -> None:
super().__init__("services/myservice/up", loop_wait = 1)
# attaches a custom coroutine to the event loop
async def custom_coroutine():
print("setup")
for i in range(3):
print(f"loop {i}")
await asyncio.sleep(1)
print("cleanup")
# we can also attach predefined coroutines (ticker) to the event loop
# runs async, waits 0.5s for next loop, then ends loop (return None = end loop)
def my_ticker(t,dt,count):
print(f"{t}, {dt}, {count}")
if count == 3:
return None
return 0.5 #seconds to wait
def run_5_times(t, dt, count):
print(count)
if count == 5:
print("end")
return None
return 0 # wait 0s for next loop
# executes callback after setup is called, return 2 means wait 2s
self.get_loop().create_ticker(run_5_times, setup=lambda: 2)
# runs custom coroutine
self.get_loop().attach_coroutine(custom_coroutine())
self.get_loop().create_ticker(my_ticker)
self.get_loop().set_timeout(lambda: print("run once after 5s"),5)
self.get_loop().set_timeout(lambda: self.backoff(),1)
def on_loop_start(self) -> None:
self.backoff()
print("loop started")
def on_loop_stop(self) -> None:
print("loop stopped")
def on_loop(self, t, dt) -> None:
# this is the main loop, it's called every 0.1 s if not otherwise setup in init
# here it's set to run every 1s with loop_wait
pass
@backoff_timer(seconds=5)
def backoff(self):
print("This is a demonstration of the backoff_timer decorator")
print("When used, the method, the method cannot be called twice within the backoff time")
print("If something tries to call the method before the backoff time, a BackoffTimerException is raised")
s = AsyncLoopExamples()
s.start()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment