gpt4 book ai didi

python - 在python中执行基于特定时间间隔的任务

转载 作者:行者123 更新时间:2023-12-03 21:28:17 25 4
gpt4 key购买 nike

我正在尝试根据设置打开和关闭 LED set_car_id在一个时间间隔内返回一些值。如果设置返回某个值,我希望 LED 更亮 8 秒。在下面显示的代码中,一旦设置返回一个值,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

最佳答案

尝试这个:

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职能。

关于python - 在python中执行基于特定时间间隔的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com