繁体   English   中英

Python:threading.timer不遵守间隔

[英]Python: threading.timer not respecting the interval

这是另一个问题的解决方案,我现在有一个解决方案,但是由于不相关的原因,该实现似乎行为不正常。

我有以下代码:

import time
import datetime
import threading

def scheduled_function(cycle):
    cycle += 1
    print "Cycle " + str(cycle) + " complete."
    print "Next cycle at " +  (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%l:%M%p")

    threading.Timer(300, scheduled_function(cycle)).start() # New cycle every 5 mins
    return

scheduled_function(1)

while(True):
    command = raw_input()
    print command

通常,这似乎可以实现我想要的功能-允许用户在后台输入命令,同时定期调用某个函数来执行某种常规活动。 但是,间隔(在这种情况下为300,应等于5分钟)似乎没有任何作用,并且程序在1秒钟左右的时间内达到了最大递归深度。 (对于实际的脚本,最大递归不是问题,因为它一次可能不会运行几个小时以上)。

我如何错误地使用threading.Timer?

那是因为您正在立即调用它,而不是让Timer为您调用它。

threading.Timer(300, scheduled_function, args=[cycle,]).start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM