Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
休眠python循环以在精确的时间进行迭代_Python_Loops_Datetime_Time - Fatal编程技术网

休眠python循环以在精确的时间进行迭代

休眠python循环以在精确的时间进行迭代,python,loops,datetime,time,Python,Loops,Datetime,Time,我有一个Python3脚本,它将全天候运行无限循环。它建立了一个网站连接并转到某个网页下载文件 每个迭代大约需要一分钟,但我需要脚本在精确的时间开始每个迭代,大约间隔5分钟。例如:一小时后1分钟,一小时后6分钟,一小时后11分钟,等等。我需要脚本在迭代之间休眠,直到重新开始的确切时间。只是想知道有没有干净的方法 编辑:根据目前给出的答案,我想我需要重新表述我的问题。基本上,需要计算上一次迭代结束到下一次迭代开始之间的时间。换句话说,我需要现在,当前时间和下一次时间之间的差值,时间的分钟是01,0

我有一个Python3脚本,它将全天候运行无限循环。它建立了一个网站连接并转到某个网页下载文件

每个迭代大约需要一分钟,但我需要脚本在精确的时间开始每个迭代,大约间隔5分钟。例如:一小时后1分钟,一小时后6分钟,一小时后11分钟,等等。我需要脚本在迭代之间休眠,直到重新开始的确切时间。只是想知道有没有干净的方法


编辑:根据目前给出的答案,我想我需要重新表述我的问题。基本上,需要计算上一次迭代结束到下一次迭代开始之间的时间。换句话说,我需要现在,当前时间和下一次时间之间的差值,时间的分钟是01,06,11,16,21,26,31,36,41,46,51,56,时间的秒数是00。然后我就可以计时了。sleep()在这段时间内运行脚本。

查看用于建立web连接的请求库,并将脚本放入cron作业中,使其每5分钟运行一次。

好吧,我相信他们称之为“kludge”。我在下面贴了一堆评论和打印行,以便澄清,看看这是怎么回事。无论如何,这似乎效果不错。每个循环将在?1:30和?6:30开始(第一个循环除外),间隔正好5分钟,并且在循环即将开始的几毫秒内开始。当然,如果您决定使用它,则需要对其进行编辑,但这可能是一个有用的开始

##### import modules
import time
import datetime
from datetime import datetime
from datetime import timedelta
##### create list of possible loop start times; this here creates start times every 5 minutes, starting the loops at 01:30, 06:30, 11:30, etc., after the hour
dt_cur = datetime.now()
dt_4_list = datetime.strptime(str(dt_cur.year) + '-' + str(dt_cur.month) + '-' + str(dt_cur.day) + ' ' + str(dt_cur.hour) + ':1:30', '%Y-%m-%d %H:%M:%S')
ls_dt = [dt_4_list]
for i in range(288):
    dt_4_list = dt_4_list + timedelta(minutes = 5)
    ls_dt.append(dt_4_list)
##### begin the loop
loop_timer = 0
while loop_timer < 275:
    if loop_timer > 0:
        ##### check if the loop started before the exact time due to time.sleep() not being exactly accurate
        time_check = datetime.now().strftime("%S.%f")
        time_check = float(time_check)
        loop_time_check = 0
        while time_check < 30 and loop_time_check < 100:
            time_check = datetime.now().strftime("%S.%f")
            time_check = float(time_check)
            print(time_check, '- WARNING: time_check < 30; loop =', loop_time_check + 1, flush=True)
            time.sleep(.025)
            loop_time_check += 1
            if loop_time_check == 100:
                print(time_check, '- WARNING: exiting script early; time_check < 30 100 times', flush=True)
                raise SystemExit()
    ########################################################################################################################
    ##### start doing  stuff here ##########################################################################################
    dt_cur = datetime.now()
    print(dt_cur, flush=True)
    for i in range(5):          ##### this is where your own script does it's work before resting until the next loop
        print(i, flush=True)
        time.sleep(1)
    ##### end doing stuff here #############################################################################################
    ########################################################################################################################
    ##### create the current datetime var
    dt_cur = datetime.now()
    print(dt_cur, flush=True)
    ##### create the dt_next_loop time var, increment the loop
    for d in ls_dt:
        if d > dt_cur:
            dt_next_loop = d
            break
    loop_timer += 1
    ##### get the seconds to sleep the script but make it about 5 seconds short of the actual time to begin the next loop
    sleep_secs = (dt_next_loop - dt_cur) - timedelta(seconds=5)
    sleep_secs = timedelta.total_seconds(sleep_secs)
    time.sleep(sleep_secs)
    ##### sleep the script about 5 seconds more before the actual time to begin the next loop (sleep.time() is not precisely accurate
    ##### over minutes and doing this again 5 seconds before the time to begin the next loop will ensure more accuracy)
    sleep_secs = datetime.now().strftime("%S.%f")
    sleep_secs = 30 - float(sleep_secs)
    time.sleep(sleep_secs)
导入模块 导入时间 导入日期时间 从日期时间导入日期时间 从日期时间导入时间增量 #####创建可能的循环开始时间列表;这里每5分钟创建一次开始时间,在一小时后的01:30、06:30、11:30等时间开始循环 dt_cur=datetime.now() dt_4_list=datetime.strtime(str(dt_cur.year)+'-'+str(dt_cur.month)+'-'+str(dt_cur.day)+'+str(dt_cur.hour)+':1:30','%Y-%m-%d%H:%m:%S') ls_dt=[dt_4_列表] 对于范围内的i(288): dt_4_列表=dt_4_列表+时间增量(分钟=5) ls_dt.append(dt_4_列表) #####开始循环 循环计时器=0 当环路定时器<275时: 如果循环计时器>0: #####检查循环是否由于time.sleep()不准确而在准确时间之前启动 time\u check=datetime.now().strftime(“%S.%f”) 时间检查=浮动(时间检查) 循环时间检查=0 当时间检查<30且循环时间检查<100时: time\u check=datetime.now().strftime(“%S.%f”) 时间检查=浮动(时间检查) 打印(时间检查“--警告:时间检查<30;循环=”,循环时间检查+1,刷新=真) 睡眠时间(.025) 循环时间检查+=1 如果循环时间检查=100: 打印(时间检查,-警告:提前退出脚本;时间检查<30 100次',刷新=真) 提升系统退出() ######################################################################################################################## #####开始在这里做事########################################################################################## dt_cur=datetime.now() 打印(dt_cur,flush=True) 对于范围(5)中的i:#######这是您自己的脚本在休息到下一个循环之前执行其工作的地方 打印(i,刷新=真) 时间。睡眠(1) #####别在这儿干了############################################################################################# ######################################################################################################################## #####创建当前日期时间变量 dt_cur=datetime.now() 打印(dt_cur,flush=True) #####创建dt_next_循环时间变量,增加循环时间 对于ls_dt中的d: 如果d>dt\u cur: dt_next_loop=d 打破 循环计时器+=1 #####获取睡眠脚本的秒数,但使其比开始下一个循环的实际时间短5秒 sleep_secs=(dt_next_loop-dt_cur)-timedelta(秒=5) 睡眠秒=时间增量。总睡眠秒(睡眠秒) 时间。睡眠(睡眠秒) #####在开始下一个循环的实际时间(sleep.time()并不精确)之前,再将脚本休眠5秒左右 #####在开始下一个循环的时间之前5秒,在几分钟内再次执行此操作将确保更高的准确性) sleep_secs=datetime.now().strftime(“%S.%f”) 睡眠秒=30-浮动(睡眠秒) 时间。睡眠(睡眠秒)
是否需要无限循环?确保程序在精确的时间运行是非常困难的,因为操作系统具有控制权。如果脚本只运行一次迭代,您可以使用crontab来控制每次迭代的启动时间。我使用Selenium访问网页,我需要保持与网站的连接处于打开状态,以便我可以在准确的时间获取下载链接。我认为,只停留在页面上要比每次登录/注销容易得多。嗯,网页是无状态的。。。所以其实没什么不同。此外,您不能永久打开web连接。如下文所述,每次下载后使用
sleep(5)
睡眠(5)你需要多少精度?如果你还有五秒钟,这有问题吗?