如何在满足 while 循环条件时跳出 time.sleep()
How to Break out of time.sleep() when while loop condition is met
我正在制作根据交通情况调整的警报。稍微弄乱之后,我决定程序最好每 15 分钟左右从 API 获取数据。但是,我注意到如果在 time.sleep() 处于活动状态时满足 while 循环条件,则在 time.sleep() 的整个持续时间结束之前它不会中断。有没有办法让它在满足条件时中断,即使在 time.sleep() 期间也是如此?提前致谢!
while datetime.datetime.now() < self.wakeuptime: #refers to alarm time
resp = requests.get(url=url, params=param)
data = json.loads(resp.content)
simplifiedtime = datetime.datetime.strptime(data["routes"][0]["legs"][0]["departure_time"]["text"], "%I:%M%p").time()
#gets suggested departure time from api
combinedsimplifiedtime=datetime.datetime.combine(today, simplifiedtime)
self.wakeuptime = combinedsimplifiedtime - datetime.timedelta(minutes=15)
#resets wakeuptime value depending on api
self.timetogo = combinedsimplifiedtime
print self.wakeuptime
time.sleep(900)
#waits 15 minutes and checks again until wakeuptime
您可以使用另一个 while 循环来比从 API 更新的循环更频繁地检查当前时间。而不是 time.sleep(900)
你可以这样做:
start_pause = datetime.datetime.now()
while (datetime.datetime.now()-start_pause).seconds < 900 \
and datetime.datetime.now() < self.wakeuptime:
time.sleep(1)
900 秒后仍然只有 运行 外循环。
我正在制作根据交通情况调整的警报。稍微弄乱之后,我决定程序最好每 15 分钟左右从 API 获取数据。但是,我注意到如果在 time.sleep() 处于活动状态时满足 while 循环条件,则在 time.sleep() 的整个持续时间结束之前它不会中断。有没有办法让它在满足条件时中断,即使在 time.sleep() 期间也是如此?提前致谢!
while datetime.datetime.now() < self.wakeuptime: #refers to alarm time
resp = requests.get(url=url, params=param)
data = json.loads(resp.content)
simplifiedtime = datetime.datetime.strptime(data["routes"][0]["legs"][0]["departure_time"]["text"], "%I:%M%p").time()
#gets suggested departure time from api
combinedsimplifiedtime=datetime.datetime.combine(today, simplifiedtime)
self.wakeuptime = combinedsimplifiedtime - datetime.timedelta(minutes=15)
#resets wakeuptime value depending on api
self.timetogo = combinedsimplifiedtime
print self.wakeuptime
time.sleep(900)
#waits 15 minutes and checks again until wakeuptime
您可以使用另一个 while 循环来比从 API 更新的循环更频繁地检查当前时间。而不是 time.sleep(900)
你可以这样做:
start_pause = datetime.datetime.now()
while (datetime.datetime.now()-start_pause).seconds < 900 \
and datetime.datetime.now() < self.wakeuptime:
time.sleep(1)
900 秒后仍然只有 运行 外循环。