mardi 29 mars 2016

Generate some "random" start times for scripts to run based on a period of time in python

I'm trying to generate some random seeded times to tell my script when to fire each of the scripts from within a main script.

I want to set a time frame of:

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

When it reaches the start time, it needs to look at how many scripts we have to run:

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

In this case there are 3 to run, so it needs to generate 3 randomized times to start those scripts with a minimum separation of 5 mins between each script but the times must be within the time set in START_TIME and END_TIME

But, it also needs to know that script1.main is ALWAYS the first script to fire, other scripts can be shuffled around (random)

So we could potentially have script1 running at 01:43 and then script3 running at 01:55 and then script2 might run at 02:59

We could also potentially have script1 running at 01:35 and then script3 running at 01:45 and then script2 might run at 01:45 which is also fine.

My script so far can be found below:

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 from file
        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 "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)




Aucun commentaire:

Enregistrer un commentaire