0

I am trying to implement a micropython Class to make a function runs forever at a certain time interval. For that I am trying to adapt the following code from this post:

class Timer:
    def __init__(self, timeout, callback):
        self._timeout = timeout
        self._callback = callback
        self._task = asyncio.create_task(self._job())

    async def _job(self):
        while True:
            await asyncio.sleep(self._timeout)
            await self._callback()

    def cancel(self):
        self._task.cancel()


async def timeout_callback():
    await asyncio.sleep(0.1)
    print('echo!')


async def main():
    timer = Timer(2, timeout_callback)  # set timer for two seconds
    await asyncio.sleep(12.5)  # wait to see timer works

asyncio.run(main())

The point is, I can't make it run indefinitely as a "normal" while loop. I have notice that the callback keeps running as per the time defines in the last await asyncio.sleep(secs) command... but this is not what I actually want to achieve. Any help would be hilly appreciated.

Eduardo
  • 57
  • 1
  • 13
  • *The point is, I can't make it run indefinitely as a "normal" while loop.* - I'm not sure I understand this point. Can you show what a normal while loop would look like, i.e. what kind of code you'd like to write? Also, you say that the callback keeps running as per time determined by the call to `asyncio.sleep()`, which is not what you want to achieve? What _do_ you want to achieve? – user4815162342 Jul 05 '21 at 09:44
  • I am writing an micropython asyncio application running on a ESP32 to steer a LED lamp using a webserver from [https://github.com/miguelgrinberg/microdot] and a button interface from [https://github.com/peterhinch/micropython-async/blob/master/v3/primitives/pushbutton.py]. Since I would like to program the lamp to switch on at a defined time, I would like to implement a asyncio Class with a function to check each 30 sec if the time to switch on has come or not. – Eduardo Jul 05 '21 at 19:07
  • 1
    Ok, I think I understand now. The premise of asyncio is that your whole program is structured as an asyncio program, i.e. that _all_ your functions are async, and are running within the confines of `asyncio.run()`. Then you would no longer need that last `asyncio.sleep()`, and the timer would naturally work alongside your application. I'm not sure if that kind of modification is feasible for your use case, just explaining the prerequisites for using asyncio. – user4815162342 Jul 05 '21 at 19:39

0 Answers0