-1

我在 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 毫秒的时间差压缩代码!

4

1 回答 1

0

它正在调用 Python 的 sleep 函数,该函数在几秒钟内接受一个参数。理想情况下,您所做的会将其转换为 0.25 秒,但所涉及的所有数字都是整数。

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

于 2013-09-26T19:19:59.157 回答