Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sleep without interfering with script?

Hey I need to know how to sleep in Python without interfering with the current script. I've tried using time.sleep() but it makes the entire script sleep.

Like for example


import time
def func1():
    func2()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()

I want it to immediately print Do stuff here, then wait 10 seconds and print Do more stuff here.
like image 678
AustinM Avatar asked Feb 27 '11 21:02

AustinM


People also ask

Is Python time sleep blocking?

The reason you'd want to use wait() here is because wait() is non-blocking, whereas time.sleep() is blocking.

What is the alternative for time sleep in Python?

The Timer is another method available with Threading, and it helps to get the same functionality as Python time sleep. The working of the Timer is shown in the example below: Example: A Timer takes in input as the delay time in Python in seconds, along with a task that needs to be started.

What does sleep () do in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds.


2 Answers

Interpreting your description literally, you need to put the print statement before the call to func2().

However, I'm guessing what you really want is for func2() to a background task that allows func1() to return immediately and not wait for func2() to complete it's execution. In order to do this, you need to create a thread to run func2().

import time
import threading

def func1():
    t = threading.Thread(target=func2)
    t.start()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()
print("func1 has returned")
like image 148
unholysampler Avatar answered Oct 16 '22 13:10

unholysampler


You could use threading.Timer:

from __future__ import print_function
from threading import Timer

def func1():
    func2()
    print("Do stuff here")
def func2():
    Timer(10, print, ["Do more stuff here"]).start()

func1()

But as @unholysampler already pointed out it might be better to just write:

import time

def func1():
    print("Do stuff here")
    func2()

def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()
like image 28
jfs Avatar answered Oct 16 '22 13:10

jfs