[英]time.sleep() function
我只是想了解,如果當我調用 time.sleep(x) 時,運行代碼的當前線程會延遲 x 秒。 但是,這會在 x 秒內釋放處理器,還是線程將資源保留給自己,並在 x 秒后才開始執行下一行代碼。
使用我面臨的確切場景進行編輯:
這是我的情況:
class SomeHandler(tornado.websocket.WebSocketHandler)
@tornado.gen.coroutine
def something_async():
time.sleep(5)
return result
def on_message(message):
future = yield something_async(message)
if __name__ == '__main__':
application = tornado.web.Application([
(r'/', SomeHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
現在,由於這個 Tornado 將是一個單線程服務器,time.sleep(5) 在這種情況下到底做了什么(它會阻塞線程 5 秒,使整個進程同步)還是協程生成一個新線程?
一個例子總是最好的:
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
from __future__ import (absolute_import, division, print_function)
# unicode_literals)
import threading
import time
def func1():
time.sleep(10)
print('Func1: Out of sleep and returning')
def func2(flag):
while not flag:
time.sleep(1)
print('Func2: looping')
print('Func2: Flag set, leaving')
t1 = threading.Thread(target=func1)
f = list()
t2 = threading.Thread(target=func2, kwargs=dict(flag=f))
t1.start()
t2.start()
t1.join()
f.append(None)
輸出:
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func1: Out of sleep and returning
Func2: looping
Func2: Flag set, leaving
從輸出中可以明顯看出,即使t1
(第一個線程)長時間處於阻塞狀態, time.sleep
10
秒,第二個線程t2
運行。
即使完成了t1
,我們仍然可以看到主線程能夠append
到列表中,該列表被用作flag
以使t2
了解它必須返回並因此結束。
因此: time.sleep
僅阻塞正在執行該線程的線程。
龍卷風從不為您生成線程。*如果您調用time.sleep,它將在整個睡眠期間阻止整個過程; 沒有其他處理繼續。 這就是為什么文檔說“ time.sleep不應該在協程中使用,因為它正在阻塞”的原因 。 要顯式暫停協程並將控制權返回給IOLoop,以便可以進行其他處理:
yield gen.sleep(0.5)
*龍卷風可以生成線程以進行DNS解析,或者在您顯式使用ThreadPoolExecutor使任務異步時。 但是您可以在此討論中忽略這些情況。
你可以使用function里面的代碼:
import time
time.sleep(2) # put value here as seconds, 2 is 2 seconds
或者
from time import sleep
sleep(60) # put value here as seconds, 60 is 60 seconds = 1 minute
示例代碼:
import time
def function1():
print('function1 is sleeping for 2 seconds...')
time.sleep(2)
count = 0
while True:
if count >= 10:
break
function1()
count=count+1
更多詳情請訪問: https://docs.python.org/3/library/time.html#time.sleep
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.