Shadowjonathan
Shadowjonathan

Reputation: 274

How to make python await for "nothing", running the event loop first

I run a python program which is run by network events and cannot go 10-15 seconds without processing heartbeats. (More specifically, I use discord.py with a pretty large volume of events)

In one of the possible scenarios I could have a command store a large amount of data into a database, this could potentially take up more than those 10 to 15 seconds, and is blocking.

These are thousands of small database calls where I could make the asynchronous event loop "run its course" in between those calls if needed. How can I make python "await for nothing" in this case?

A similair hack would be to await for a resolved Promise in JavaScript, which throws the process back into the event loop, resolving more pressing events first.

Upvotes: 5

Views: 4796

Answers (1)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39576

await asyncio.sleep(0) - is a way to return control to an event loop.

Although instead of constantly calling it you may go another way: run your blocking code in another thread using run_in_executor and awaiting for it to be finished. This way event loop will normally continue it's course while blocking stuff being processed in background thread.

Upvotes: 9

Related Questions