I have a function that collects data from an api every 60 seconds. I want to be able to start and stop this function by making request to Python Flask app. The app is deployed on a VPS server, but what I noticed is that thread would just automatically stops after some time. If I send “start” request thread would start working again.
So, my questions are:
- Is it a good approach I am using?
- How do I make thread running until ‘stop’ request is received?
Here is my code:
# Thread that runs the main function
thread = None
stop_thread = True
def main():
print("Starting the application...")
try:
while stop_thread is False:
try:
conn = connect_to_db()
# Some API interaction here
conn.commit()
except Exception as e:
print(f"An error occurred: {e}")
conn.rollback()
finally:
conn.close()
time.sleep(60) # Sleep for 60 seconds
finally:
conn.close()
@app.route("/start", methods=["POST"])
def start():
global thread
global stop_thread
if thread is None:
stop_thread = False
thread = threading.Thread(target=main)
thread.start()
return jsonify({"status": "started"})
return jsonify({"status": "already started"})
@app.route("/stop", methods=["POST"])
def stop():
global thread
global stop_thread
if thread is not None:
stop_thread = True
thread.join()
thread = None
return jsonify({"status": "stopped"})
return jsonify({"status": "not started"})
if __name__ == "__main__":
app.run(debug=True)
Currently I am creating separate thread when request to the “/start” endpoint is received. Inside my function I have while loop that checks global boolean flag. So, the idea is:
- Accept “start” request
- Change global flag to true
- Start fetching function in a separate thread
- Fetch data from api while flag is true.
- Accept “stop” request
- Change global flag, join thread.
I do not want it to be some kind of cron job because I want to be able to control data fetching process from a client side later.