你需要把你想在推遲該計劃的一部分其自己的線程,然後在該線程中調用sleep()。
我不知道到底是什麼你想在你的例子做的,所以這裏是一個簡單的例子:
import time
import threading
def print_time(msg):
print 'The time %s is: %s.' % (msg, time.ctime(time.time()))
class Wait(threading.Thread):
def __init__(self, seconds):
super(Wait, self).__init__()
self.seconds = seconds
def run(self):
time.sleep(self.seconds)
print_time('after waiting %d seconds' % self.seconds)
if __name__ == '__main__':
wait_thread = Wait(5)
wait_thread.start()
print_time('now')
輸出:我們一開始的線程將
The time now is: Mon Jan 12 01:57:59 2015.
The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015.
公告首先等待5秒,但它不會阻止print_time('now')調用,而是等待在後臺。
編輯:
從JF Sebastian的評論,與線程的簡單的解決方法是:
import time
import threading
def print_time(msg):
print 'The time %s is: %s.' % (msg, time.ctime(time.time()))
if __name__ == '__main__':
t = threading.Timer(5, print_time, args = ['after 5 seconds'])
t.start()
print_time('now')
哪功能?您發佈的代碼中沒有功能。 –
'好的',你必須更具體。 – GLHF
你說你想「在不暫停整個程序的情況下延遲一部分程序」。好的,那麼你的程序在延遲時間內會做什麼,什麼時候它不是*畫烏龜? –