新聞中心
Thread類有一個(gè)Timer子類,該子類可用于控制指定函數(shù)在特定時(shí)間內(nèi)執(zhí)行一次。例如如下程序:

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


咨詢
建站咨詢
