Python 在Raspberry Pi上使用timer2时出现的问题

Python 在Raspberry Pi上使用timer2时出现的问题,python,timer,raspberry-pi,Python,Timer,Raspberry Pi,我在覆盆子圆周率上使用timer2有问题 这是密码 ************************************************************** # tmr2_tst_04.py # https://github.com/ask/timer2 # http://pymotw.com/2/threading/index.html#thread-objects # ISSUES: # # *) Seems to respond only to even

我在覆盆子圆周率上使用timer2有问题

这是密码

************************************************************** 
#  tmr2_tst_04.py
#  https://github.com/ask/timer2
#  http://pymotw.com/2/threading/index.html#thread-objects
# ISSUES:
#
#   *)  Seems to respond only to even seconds
#
#   *)  Is off by 1 second.  i.e.  4000 gives a 5 second interrupt

import timer2
import time       #  for sleep
import signal,sys

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    timer.stop()
    sys.exit(0)

#time_to_wait = 4500
#time_to_wait = 4999
time_to_wait = 4000.0    #  gives 5-second cycle time !!!
#time_to_wait = 500.0     #  doesn't work

tm = 0
tdiff = 0
tm_old = -1
iter = 0
to_print = False

def hello():
    global iter
    global tm, tdiff
    global tm_old
    global to_print

    tm = time.time()
    tdiff = (tm - tm_old) if tm_old > 0  else  0
    tm_old = tm
    iter += 1


#   buf = "%3d %d %f %6.4f %s" % (iter, time_to_wait, tm, tdiff, "Hello world")
#   print buf
    to_print = True

#    Set up to catch ^C
signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl+C to exit'

#   Set up timer interrupt routine
timer = timer2.Timer()
timer.apply_interval(time_to_wait, hello)



#  Main program loop
while iter <= 10000:
    if to_print:
        buf = "%3d %d %f %6.4f %s" % (iter, time_to_wait, tm, tdiff, "Hello world")
        print buf
        to_print = False
    time.sleep((time_to_wait/1000)/2)

timer.stop()

*************************************************************************

它根本不起作用-只需在代码中以0.1毫秒的时差进行压缩

它调用Python的sleep函数,该函数以秒为单位获取参数。理想情况下,您所做的将转换为.25秒,但所有涉及的数字都是整数


作为整数,500/1000=0,0/2=0,依此类推。因此,它在继续之前等待请求的0秒。例如,将1000更改为1000.0,它应该可以工作。

您可以扩展到“它根本不工作”吗?谢谢!所以,正如我理解你的答案,timer2函数只在整数秒内工作-对吗?我想知道为什么时间是以毫秒为单位的。。。。。。尽管如此,对于4000的“等待时间”值,Pi上仍存在5秒延迟和UBUNTU上4秒延迟的问题。谢谢!所以,正如我理解你的答案,timer2函数只在整数秒内工作-对吗?我想知道为什么时间是以毫秒为单位的。。。。。。尽管如此,对于4000的“等待时间”值,Pi上仍存在5秒延迟和UBUNTU上4秒延迟的问题。谢谢!所以,正如我理解你的答案,timer2函数只在整数秒内工作-对吗?我想知道为什么时间是以毫秒为单位的。。。。。。尽管如此,Pi上仍存在5秒延迟和UBUNTU上4秒延迟的问题,即“等待时间”值为4000。我已经查看了timer2的文档,但在文档中找不到它说只使用整数秒是好的-你能告诉我正确的文档页面吗?我根本没有说timer2,我说的是你输入的内容。您已经输入了整数,所以它将进行整数除法,因此您得到的答案是0(在python shell中尝试一下,您将看到)。如果你让它们浮动,它就不会发生,你有机会做出你想要的行为。
time_to_wait = 500