Python:threading.timer不遵守间隔 [英] Python: threading.timer not respecting the interval

查看:407
本文介绍了Python:threading.timer不遵守间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有以下代码:

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秒钟左右的时间内达到了最大递归深度. (对于实际的脚本,最大递归不是问题,因为它一次最多不会运行几个小时.)

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).

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

How am I using threading.Timer wrongly?

推荐答案

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

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()

这篇关于Python:threading.timer不遵守间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆