I've see this question a lot but I'm not satisfied with the answers. I know server programs like Django and Flask/Werkzeug have startserver/run method that keeps the process alive until a stop signal is received.
I want to implement something similar but I cannot figure out how to do it. I assume that an eternal loop is a bad way to do it because it is wasted processing time. I'd rather not use a third party library.
My program must stay alive to wait for callbacks, communicate with a server, monitor its internal state, etc.
Pseudocode:
import ...
class Main():
def __init__():
self.sensors = sensors.register()
self.database = remote.connect()
self.running = True
def start():
""" this is what I assume is bad """
while self.running:
pass
def stop():
self.running = False
self.cleanup()
def cleanup():
self.database.disconnect()
self.sensors.unregister()
There is a general paradigm not specific to python to deal with this kind of situation called event loops. If you search for it on the internet, you will find several libraries implementing it. If you use asyncio you do not need third party libraries as it ships with python3. I would advise you to familiarize yourself with the concept, the web is full of examples. See e.g. this tutorial. We get this example from there:
import asyncio
async def work():
while True:
await asyncio.sleep(1)
print("Task Executed")
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(work())
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
loop.close()
I hope this helps.
You could:
import time
time.sleep(x) #seconds
And only check status at the desired interval.
For network events you could use sockets. https://python-socketio.readthedocs.io/en/latest/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With