如何在满足while循环条件时中断time.sleep()

时间:2017-03-11 07:03:11

标签: python time while-loop alarm python-datetime

我正在根据流量进行调整。搞砸了一下之后,我认为程序最好每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

1 个答案:

答案 0 :(得分:1)

您可以使用另一个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秒后运行外循环。