我在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 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()
*************************************************************************
这在Raspberry Pi上每5000毫秒运行一个“hello”线程,但在UBUNTU机器上每4000毫秒运行
第二个问题 - 如果我尝试短时间间隔,请说
time_to_wait = 500
它完全不起作用 - 只需在时间差为.1毫秒的时间内完成代码!
答案 0 :(得分:0)
它正在调用Python的sleep函数,该函数在几秒钟内获取参数。理想情况下,你所做的将把它转换为.25秒,但所涉及的所有数字都是整数。
作为整数,500/1000 = 0,0 / 2 = 0,依此类推。因此,它会在继续之前等待请求的0秒。例如,将1000更改为1000.0,它应该可以正常工作。