我有以下代码,并且陷入了while循环
我知道while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
行存在问题。
有人可以帮忙吗?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)
答案 0 :(得分:3)
您询问当前时间是否小于当前时间加上delta。当然,每次都会如此,未来总是会走得更远。
记录的开始时间:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
如果wait_time
在循环中没有变化,请存储结束时间(当前时间加上delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
在这里使用time.time()
可能更容易:
end = time.time() + 60 * wait_time
while time.time() < end:
答案 1 :(得分:2)
你在while循环中使用datetime.datetime.now()
,这意味着你检查每次迭代是否现在的时间低于现在的时间+ delta。
这在逻辑上是错误的,因为它将永远是真的,因为现在的时间总是低于现在的时间加上delta。
您应该将其更改为:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"