简体   繁体   English

Python:threading.timer不遵守间隔

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

This is a followup to another question , to which I now have a solution but the implementation doesn't seem to be behaving properly for unrelated reasons. 这是另一个问题的解决方案,我现在有一个解决方案,但是由于不相关的原因,该实现似乎行为不正常。

I have the following code: 我有以下代码:

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

In general this seems to accomplish what I want - allowing the user to enter commands while in the background while a function is periodically called to do some sort of regular activity. 通常,这似乎可以实现我想要的功能-允许用户在后台输入命令,同时定期调用某个函数来执行某种常规活动。 However, the interval (300 in this case, which should equate to 5 minutes) does not seem to be doing anything, and the program reaches maximum recursion depth within a second or so. 但是,间隔(在这种情况下为300,应等于5分钟)似乎没有任何作用,并且程序在1秒钟左右的时间内达到了最大递归深度。 (Max recursion is not a problem for the actual script, as it likely won't be run for more than a few hours at a time). (对于实际的脚本,最大递归不是问题,因为它一次可能不会运行几个小时以上)。

How am I using threading.Timer wrongly? 我如何错误地使用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