I have a function def event(...) in my EventHandler class which can be called at arbitrary intervals in my main code. It needs to put all the events that are coming in into a queue and process them one at a time. How do I do this? I've been trying to use the asyncio library to do this, but I have no clue how to do it. My problem is that if I make event async, then I get the error that it was never awaited. If I don't make it async, then I can't call the function that processes the next item in the queue.
async def _event(...):
queue_item = await(self._queue.get())
...
I need to be able to call event at any time, but the helper function _event needs to processes the next item in queue one at a time.
How do I solve this?
I tried making event synchronous
def event(...):
"""
When an event happens, this will add it to the queue. Multiple events can happen, and they will be executed one at a time, as they come in. Later on, we can change this.
"""
self._queue.put_nowait((flag, *args))
task = self._loop.create_task(self._event())
asyncio.ensure_future(task)
but then the error that comes up is that task was not awaited.
Pending more details from the poster, here is an example that has a
MainThreadClassrunning on the main thread of a program and anasyncioevent loop running on another thread. WhenMainThreadClass.eventis called, it sends a message to the event loop via anasyncio.Queueandasyncio.run_coroutine_threadsafe. From there, theasyncioevent loop is continuously listening for messages on the queue and processes the message, printing it to the console.This program prints the following to the console: