I am trying to start create a thread to run a process (task function), but only creating the thread if the thread is not already running, and run only once. The main.py will be refreshed regularly and trigger the thread process to run in the background. This is so that I can save on compute resources. For example, if users refresh my page 3 times, the process goes on to run 3 threads, but I am trying to do so it only run once within the 10 seconds(during sleep). I just need the first time to work and trigger the thread/task and ignore subsequent triggers. I have created a script that I think should be working but it runs tasks every time main() runs, when it shouldn’t.
I have created a try except to check if the current_thread is existing, if it is existing to check if its not running with the ‘is_alive()’ method, and if not to ignore(and not proceed) if it exists and still “is_alive()”. If the exception triggers, the current_thread does not exist and the script proceeds to start a new thread (current_thread). Based on the logic in the script, It looks like current_thread.is_alive() is not working since I have a thread running but its still triggering new current_thread.start().
import time import threading def task(): print ('start task') time.sleep(10) print ('task complete') current_thread = threading.Thread(target=task) def main(): try: if not current_thread.is_alive(): current_thread.start() current_thread.join() except UnboundLocalError as e: current_thread.start() current_thread.join() if __name__ == '__main__': main()
While I found a answer that is related (it only runs a new thread when the old one finishes running), the script is not very useful since it runs infinitely, while I only want the thread to run one time. python – start a thread if it’s not already running.
Any help on what I am missing or what can be done to fix this is appreciated.
Check is_alive property to start a thread only if previous one has finished running.
import threading def numbers(num): for i in range(0, num): print(i) current_thread = None while True: if current_thread is None or not current_thread.is_alive(): current_thread = threading.Thread(target=numbers, args=) current_thread.start() # do something else