Python: threading.timer not respecting the interval

纵然是瞬间 提交于 2020-01-05 02:42:06

问题


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. (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?


回答1:


That's because you are calling it right away and not letting the Timer call it for you.

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


来源:https://stackoverflow.com/questions/32287024/python-threading-timer-not-respecting-the-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!