我试图生成一些随机的种子时间来告诉我的脚本何时从主脚本中触发每个脚本。

我想设定一个时间范围:

START_TIME = "02:00"
END_TIME = "03:00"


当到达开始时间时,它需要查看我们必须运行多少个脚本:

script1.do_proc()
script2.alter()
script3.noneex()


在这种情况下,要运行3个,因此它需要生成3个随机时间来启动这些脚本,每个脚本之间的最小间隔为5分钟,但时间必须在START_TIMEEND_TIME中设置的时间之内。

但是,还需要知道script1.main始终是第一个触发的脚本,其他脚本可以随机播放(随机)

因此,我们有可能让script1在01:43运行,然后script3在01:55运行,然后script2可能在02:59运行

我们还可能有script1在01:35运行,然后script3在01:45运行,然后script2可能在01:45运行,这也很好。

到目前为止,我的脚本可以在下面找到:

import random
import pytz
from time import sleep
from datetime import datetime

import script1
import script2
import script3

START_TIME = "01:21"
END_TIME = "03:00"

while 1:
    try:

        # Set current time & dates for GMT, London
        CURRENT_GMTTIME = datetime.now(pytz.timezone('Europe/London')).strftime("%H%M")
        CURRENT_GMTDAY = datetime.now(pytz.timezone('Europe/London')).strftime("%d%m%Y")
        sleep(5)

        # Grab old day for comparisons
        try:
            with open("DATECHECK.txt", 'rb') as DATECHECK:
                OLD_DAY = DATECHECK.read()
        except IOError:
             with open("DATECHECK.txt", 'wb') as DATECHECK:
                DATECHECK.write("0")
                OLD_DAY = 0

        # Check for new day, if it's a new day do more
        if int(CURRENT_GMTDAY) != int(OLD_DAY):
            print "New Day"

            # Check that we are in the correct period of time to start running
            if int(CURRENT_GMTTIME) <= int(START_TIME.replace(":", "")) and int(CURRENT_GMTTIME) >= int(END_TIME.replace(":", "")):
                print "Correct time, starting"

                # Unsure how to seed the start times for the scripts below

                script1.do_proc()
                script2.alter()
                script3.noneex()

                # Unsure how to seed the start times for above

                # Save the current day to prevent it from running again today.
                with open("DATECHECK.txt", 'wb') as DATECHECK:
                    DATECHECK.write(CURRENT_GMTDAY)

                print "Completed"

            else:
                pass
        else:
            pass

    except Exception:
        print "Error..."
        sleep(60)


编辑31/03/2016

假设我添加以下内容

SCRIPTS = ["script1.test()", "script2.test()", "script3.test()"]
MAIN_SCRIPT = "script1.test()"
TIME_DIFFERENCE = datetime.strptime(END_TIME, "%H:%M") - datetime.strptime(START_TIME, "%H:%M")
TIME_DIFFERENCE = TIME_DIFFERENCE.seconds



现在,我们有要运行的脚本数量
我们有要运行的脚本列表。
我们有主脚本的名称,第一个要运行。
我们有时间(以秒为单位)显示总共有多少时间来运行其中的所有脚本。


当然,有一种方法我们可以插入某种循环以使其全部完成。


for i in range(len(SCRIPTS)),是3次
生成3个种子,确保最短时间为300,并且这3个种子的总和不得超过TIME_DIFFERENCE
根据RUN_TIME = START_TIME然后按RUN_TIME = RUN_TIME + SEED[i]创建开始时间
第一个循环将检查MAIN_SCRIPT中是否存在SCRIPTS,如果存在,它将首先运行该脚本,从SCRIPTS中删除​​自身,然后在下一个循环中,因为SCRIPTS中不存在它。切换为随机调用其他脚本之一。


播种时代

下列方法似乎可行,但是可能有更简便的方法。

CALCULATE_SEEDS = 0
NEW_SEED = 0
SEEDS_SUCESSS = False
SEEDS = []

while SEEDS_SUCESSS == False:
    # Generate a new seed number
    NEW_SEED = random.randrange(0, TIME_DIFFERENCE)

    # Make sure the seed is above the minimum number
    if NEW_SEED > 300:
        SEEDS.append(NEW_SEED)

    # Make sure we have the same amount of seeds as scripts before continuing.
    if len(SEEDS) == len(SCRIPTS):

        # Calculate all of the seeds together
        for SEED in SEEDS:
            CALCULATE_SEEDS += SEED
        # Make sure the calculated seeds added together is smaller than the total time difference
        if CALCULATE_SEEDS >= TIME_DIFFERENCE:
            # Reset and try again if it's not below the number
            SEEDS = []
        else:
            # Exit while loop if we have a correct amount of seeds with minimum times.
            SEEDS_SUCESSS = True

最佳答案

使用datetime.timedelta计算时差。此代码假定所有三个进程都在同一天运行

from datetime import datetime, timedelta
from random import randint

YR, MO, DY = 2016, 3, 30
START_TIME = datetime( YR, MO, DY, 1, 21, 00 )   # "01:21"
END_TIME = datetime( YR, MO, DY, 3, 0, 0 )       # "3:00"
duration_all = (END_TIME - START_TIME).seconds
d1 = ( duration_all - 600 ) // 3
#
rnd1 = randint(0,d1)
rnd2 = rnd1 + 300 + randint(0,d1)
rnd3 = rnd2 + 300 + randint(0,d1)
#
time1 = START_TIME + timedelta(seconds=rnd1)
time2 = START_TIME + timedelta(seconds=rnd2)
time3 = START_TIME + timedelta(seconds=rnd3)
#
print (time1)
print (time2)
print (time3)


rnd1rnd2rnd3的值至少相隔5分钟(300秒)。

rnd3的值不能大于总时间间隔(3 * d1 + 600)。因此,这三个时间都发生在间隔内。

注意:您没有指定每个脚本运行多少时间。这就是为什么我不使用time.sleep的原因。可能的选项是threading.Timer(请参阅python文档)。

关于python - 根据一段时间在python中生成一些“随机”开始时间以使脚本运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36298398/

10-14 18:42
查看更多