【问题标题】:Performing a task based in specific time interval in python在python中基于特定时间间隔执行任务
【发布时间】:2018-03-11 06:47:16
【问题描述】:

我正在尝试根据一组set_car_id 在某个时间间隔内返回某个值来打开和关闭 LED。如果设置返回某个值,我希望 LED 亮 8 秒。在下面显示的代码中,一旦 set 返回一个值,LED 就会亮起 8 秒。但是,如果设置在 5 秒(8 秒内)返回一个值,那么 LED 将在接下来的 13 秒之前不会打开,它会再亮 3 秒然后突然关闭。我只展示了一小部分代码。有什么解决的建议吗?

last_bright_time = None            
last_dim_time = None
new_action = -1
def LED_control(set_car_id):
    global last_bright_time
    global last_dim_time
    curr_time = time.time()
    should_remain_bright = False
    should_remain_dim = False
    if (new_action == 0):      #new_action ==0 corresponds to set_car_id returning some value
        if last_bright_time == None:
            last_bright_time = time.time()
        if  (curr_time - last_bright_time) < 8:
        should_remain_bright = True
    if  ((len(set_car_id) > 0) or should_remain_bright = True):
        car_light(1)                # function to bright the LED
        last_dim_time = None
    else:
         car_light(0)               # function to dim the LED
         last_bright_time = None

【问题讨论】:

  • 不清除last_*_time变量如何,让你的状态机真正记住一些东西?
  • @M.Prokhorov 我必须清除last_*_time 变量,因为在调用car_light 函数后,我需要清除它们,因为它的状态从亮变为暗或暗变为亮发生了。
  • 好吧,如果你必须,那么这就是你得到的行为。

标签: python function if-statement time


【解决方案1】:

试试这个:

import time
while True:
    brighten()
    time.sleep(8)
    dim()
    time.sleep(8)

如果你想要更精确的东西:

import time
def sleep():
    time_start = time.time()
    while time.time() < time_start + 8000:
        pass
while True:
    brighten()
    sleep()
    dim()
    sleep()

在上面的代码片段中,您必须定义brightendim 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 2012-06-08
    • 1970-01-01
    • 2010-11-05
    • 2018-05-17
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多