天天看點

python帶參數的函數_在python中每X秒執行一個函數(帶參數)

正如其他人指出的那樣,錯誤是因為你沒有将正确的參數傳遞給threading.Timer()方法.在5秒後更正将運作您的功能一次.有很多方法可以讓它重複.

一個object-oriented方法是派生一個新的threading.Thread子類.雖然可以建立一個特别符合你想要的 – 即列印“%s”%hello – 但是制作一個更通用的參數化子類隻會稍微困難一些,它将調用一個傳遞給它的函數.執行個體化(就像threading.Timer()).如下圖所示:

import threading

import time

class RepeatEvery(threading.Thread):

def __init__(self, interval, func, *args, **kwargs):

threading.Thread.__init__(self)

self.interval = interval # seconds between calls

self.func = func # function to call

self.args = args # optional positional argument(s) for call

self.kwargs = kwargs # optional keyword argument(s) for call

self.runable = True

def run(self):

while self.runable:

self.func(*self.args, **self.kwargs)

time.sleep(self.interval)

def stop(self):

self.runable = False

def greeting(hello):

print hello

thread = RepeatEvery(3, greeting, "Hi guys")

print "starting"

thread.start()

thread.join(21) # allow thread to execute a while...

thread.stop()

print 'stopped'

輸出:

# starting

# Hi guys

# Hi guys

# Hi guys

# Hi guys

# Hi guys

# Hi guys

# Hi guys

# stopped

除了重寫基本線程.Thread類的__init __()和run()方法之外,還添加了一個stop()方法,以允許在需要時終止線程.我還簡化了greeting()函數中的列印“%s”%hello,隻列印hello.