python threading timer没执行,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.

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值