我在 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
它根本不起作用 - 只需以 0.1 毫秒的时间差压缩代码!