Coleyman
Coleyman

Reputation: 33

Python - Countdown timer function as background process

I'm new to python, so any help you can provide is much appreciated.

I have the following function :

import time

def countdown():
    my_timer = 10
    while my_timer > 0:
        time.sleep(5)
        my_timer -= 1

What I'm looking to do is during the script, call this function and send it to the background so that the rest of the script can execute - however, during the execution of the script I want to be able to "reach in" and grab the value of "my_timer" (obviously before it hits 0).

It doesn't specifically have to be a function - just as long as I can push the timer into the background and continue on with the rest of the script, while also being able to retrieve the value.

I've looked at subprocess and threading, however I'm struggling to get my head around it, and a lot of the examples I've found tend to be quite complicated.

Can anyone point me in the right direction?

Many thanks

Upvotes: 0

Views: 1378

Answers (1)

Coleyman
Coleyman

Reputation: 33

There is most likely a better way to go about this but in the end I resolved this by setting my_timer as a global variable and then starting the function by using a thread :

import time
import threading

def countdown():
    global my_timer
    my_timer = 10
    while my_timer > 0:
        time.sleep(5)
        my_timer -= 1

countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()

Upvotes: 1

Related Questions