In my program ( Python 3.5
) I want to execute a function at a certain time regardless of what phase of the code it is in. But I don't know of any statement that checks all the time (even in the course of the program) what time it is and if it is, for example, 13:15 to execute that function. A while
would not work because it would always be executing the loop but not executing the program. Any solution?
My OS is Windows 7 Ultimate.
A possible solution is to implement a thread to execute a timer and execute the function when the condition is met. In this way the main thread can continue to function without problems.
Here is an implementation example. The code has comments to clarify what is being done and an example of use.
Test code output:
Since the code has so many comments and standard output, I leave a 'clean' version of it that only includes the class
Temporizador
and without console progress information:As long as the thread is active, the function will be executed every day at that time until it is stopped using the
stop()
. When you want to end the program, use this method first to make sure the thread ends correctly.All modules belong to the standard library of
Python
( datetime , time , threading ) and the code works without modifications asPython 2.7
well.If you need to share information between what is being processed in the timed thread and your main program, use some secure method of inter-thread communication, such as a queue ( Queue ).