以下函数用于运行循环20分钟,处理SQL任务(如果可用)。为了避免在没有任何要处理的情况下进行过多的SQL调用,它应该在尝试再次处理任务之前休眠5秒钟:
def main():
sql = 'some sql task here;'
stop_time = datetime.today() + timedelta(minutes = 20)
print('Started at ', datetime.now())
print('Should stop at', stop_time)
load_more_rows = True
with ConnectionParameters.get_conn() as conn:
while load_more_rows or (datetime.now() < stop_time):
try:
res = get_num_processed_batches(conn, sql)
processed_batch = res > 0
except Exception as ex:
log_error(repr(ex))
processed_batch = False
if not processed_batch:
print('Sleeping at ', datetime.now())
time.sleep(seconds=5)
load_more_rows = processed_batch
print('Finished iteration at ', datetime.now())
print('Stopped at ', datetime.now())
不幸的是,不是睡觉,醒来,继续处理任务直到时间到了,它只是完全停止执行,如输出所示:
('Started at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 206652))
('Should stop at', datetime.datetime(2015, 3, 31, 17, 51, 6, 206630))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 356698))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 614349))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 638210))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 765645))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 6, 885282))
('Finished iteration at ', datetime.datetime(2015, 3, 31, 17, 31, 7, 12109))
('Sleeping at ', datetime.datetime(2015, 3, 31, 17, 31, 7, 13803))
我做错了什么?
答案 0 :(得分:4)
time.sleep
不接受关键字参数seconds
:
time.sleep(5)
我不确定为什么它不会引发错过必需参数的错误。
https://docs.python.org/2/library/time.html#time.sleep
>>> time.sleep(seconds=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sleep() takes no keyword arguments
>>> time.sleep(1)
>>> "everything is fine"