簡體   English   中英

Python計時器未按預期等待

[英]Python timer not waiting as expected

所以,我有這段代碼:

t = threading.Timer(570.0, reddit_post(newmsg))
t.start()

開始快速Reddit帖子。 可悲的是,它沒有等待570秒,而是自動執行reddit_post而不實際等待。

我該怎么做才能解決此問題?

那是因為當您說t = threading.Timer(570.0, reddit_post(newmsg))實際上是在調用函數而不是將參數傳遞給Timer類。

您需要做的是:

threading.Timer(570.0, reddit_post, [newmsg]).start()

請參閱Timer類文檔

要更詳細地解釋:

調用Timer構造函數時,應給它三個參數。 第一個參數應該是您希望計時器等待多長時間。 第二個參數應該是可調用的(例如一個函數)。 第三個參數應該是用來調用函數的參數列表。

一個例子。

# First we define a function to call.
def say_hello(name):
    print('hello ' + name)

# Now we can call this function.
say_hello('john')

# But when we make a timer to call it later, we do not call the function.
timer = threading.Timer(10, say_hello, ['john'])
timer.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM