Search code examples
pythontimesleep

How do I run a task in the background with a delay?


I have the following code:

import time


def wait10seconds():
    for i in range(10):
        time.sleep(1)

    return 'Counted to 10!'


print(wait10seconds())

print('test')

Now my question is how do you make print('test') run before the function wait10seconds() is executed without exchanging the 2 lines.

I want the output to be the following:

test
Counted to 10!

Anyone know how to fix this?


Solution

  • You can use Threads for this

    like:

    from threading import Thread
    my_thread = Thread(target=wait10seconds) # Create a new thread that exec the function
    my_thread.start() # start it
    print('test') # print the test
    my_thread.join() # wait for  the function to end