I have a simple requirement, when an event occurs a thread is created and sleeps for x minutes before waking up to carry out its tasks and terminate.
But if another event occurs any thread that is sleeping should be terminated and a new thread should be spawned for the same purpose.
In python I believe the best way to make a thread sleep is,
import time
time.sleep(x*60)
Is there a way to learn the state of a thread (currently sleeping/idle or alive)?
There is really no way to do this well as a thread is either alive(running) or not. Technically even if its sleeping it still running/alive its just not doing anything.
In general using sleeps in a thread is not really desirable as it can be a pain to adjust the time it sleeps and/or wake it when you need it to do something.
One thing I have used in the past for this is Condition in the threading module. This allows you to put a thread to "sleep" by calling .wait(). You can then to an .acquire(false) to see if its blocked, and then .acquire() .notify() .release() to wake it up again if you need to.
Its a simple way to keep a thread around and from spinning or using come crazy sleep paradigm.
Another good option is just to have the thread consume in a while True from a blocking queue (Queue module in python) which will technically manage all that for you.
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