掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
Thread類有一個Timer子類,該子類可用于控制指定函數(shù)在特定時間內(nèi)執(zhí)行一次。例如如下程序:

十載的橫縣網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。營銷型網(wǎng)站建設(shè)的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整橫縣建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)從事“橫縣網(wǎng)站設(shè)計”,“橫縣網(wǎng)站推廣”以來,每個客戶項目都認(rèn)真落實執(zhí)行。
from threading import Timer
def hello():
print("hello, world")
# 指定10秒后執(zhí)行hello函數(shù)
t = Timer(10.0, hello)
t.start()上面程序使用 Timer 控制 10s 后執(zhí)行 hello 函數(shù)。
需要說明的是,Timer 只能控制函數(shù)在指定時間內(nèi)執(zhí)行一次,如果要使用 Timer 控制函數(shù)多次重復(fù)執(zhí)行,則需要再執(zhí)行下一次調(diào)度。
如果程序想取消 Timer 的調(diào)度,則可調(diào)用 Timer 對象的 cancel() 函數(shù)。例如,如下程序每 1s 輸出一次當(dāng)前時間:
from threading import Timer
import time
# 定義總共輸出幾次的計數(shù)器
count = 0
def print_time():
print("當(dāng)前時間:%s" % time.ctime())
global t, count
count += 1
# 如果count小于10,開始下一次調(diào)度
if count < 10:
t = Timer(1, print_time)
t.start()
# 指定1秒后執(zhí)行print_time函數(shù)
t = Timer(1, print_time)
t.start()上面程序開始運行后,程序控制 1s 后執(zhí)行 print_time() 函數(shù)。print_time() 函數(shù)中的代碼會進行判斷,如果 count 小于 10,程序再次使用 Timer 調(diào)度 1s 后執(zhí)行 print_time() 函數(shù),這樣就可以控制 print_time() 函數(shù)多次重復(fù)執(zhí)行。
在上面程序中,由于只有當(dāng) count 小于 10 時才會使用 Timer 調(diào)度 1s 后執(zhí)行 print_time() 函數(shù),因此該函數(shù)只會重復(fù)執(zhí)行 10 次。

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流