Search code examples
pythontimersleepcountdown

How to program a task with a timer in my Python code?


I want to execute a task after certain time, so I have tried a countdown timer with a condition of being finished (when countdown variable = 0, the task is performed). The thing is that I don't want to stop the execution of the main program while performing the countdown. I have tried this:

import time

def countdown(num_of_secs):
    while(num_of_secs):
        time.sleep(1)
        num_of_secs -= 1
        return num_of_secs

So, I run my code setting a number of seconds to the countdown, and when this countdown reaches the 0 value, a task must be executed. Using this code (it uses a while), when I call my function "countdown" it stops the execution of the main program, so it is the same as a big time.sleep. I want to carry out this countdown in the background, without stopping other actions until the countdown finishes and the task starts. Thank you


Solution

  • Another alternative is by using threading. I've got a simple example here with 2 Threads where the working thread is waiting for the countdown thread to finish and starting. The Main is still working fine.

    import threading
    import time
    
    
    def do_something():
        countdown_thread.join()
        print("Starting Task")
        time.sleep(3)
        print("Finished Task")
    
    def countdown(num_of_secs):
        while(num_of_secs):
            time.sleep(1)
            num_of_secs -= 1
            print(num_of_secs)
    
    
    if __name__ == '__main__':
        countdown_thread = threading.Thread(target=countdown, args=(3,))
        work_thread = threading.Thread(target=do_something)
    
        countdown_thread.start()
        work_thread.start()
    
        while True:
            print("Main doing something")
            time.sleep(1)
    

    Example picture for multithreading: Sequential vs Threading