i m writing a script in which threads that do simple tasks start every 3 minutes . I m using the threading and schedule modules .
Because of the nature of multi-threading threads are using the same resources .
What i need to achieve ?
When creating a new thread i would like to check if there is any runningthread; and if there is , then wait until the running thread terminates , then start the new thread .
What i have tried ?
import threading
def run_threaded(job_fn):
job_thread = threading.Thread(target=job_fn)
bot.logger.info(" --------------No of active threads : "+threading.activeCount())
job_thread.start()
job_thread.join()
bot.logger.info(" --------------No of active threads : " + threading.activeCount())
schedule.every(3).minutes.do(run_threaded, job)
while True:
schedule.run_pending()
Note: On the example above every job_thread needs 5 minutes to complete . Thus it creates 1 thread every 6 minutes .
From what i understand , the job_thread.join() line is joining the main thread ( with any other active threads) . Although the schedule , is blocked thus no any other thread can be instantiated before the previous thread is finished . Is that correct ? And if yes , is this a good practice of doing this .?
And for the record .. Can the script execute other blocks of code while running a thread ? Or can it instantiate other threads, before the previous thread is finished , if they are going to execute an other job let's say job2 ?
schedulerun is: (1) start work thread, (2) wait for work thread to end, then there is no point in creating a work thread at all. You can just do the same work in your main thread. The advantage of multithreading is that different threads can be executing at the same time. If you don't want/need to do multiple things at the same time, you don't need to use multithreading.