Merv Merzoug
Merv Merzoug

Reputation: 1237

python schedule module to periodically run a function

Goal: run a function every day at a randomized time between two times.

So, I wrote this function to randomly generate a time (please offer feedback on how to streamline. Couldn't find this in an existing package - it MUST already exist...)

def gen_rand_time(low, high):
    hour = np.random.randint(low, high)
    minute = np.random.randint(1,59)
    if minute < 10:
        time = str(hour)+':'+str(0)+str(minute)
        return time
    else:
        time = str(hour) + ':' + str(minute)
        return time

Next I define the function I would like to run. Keeping it nice and simple.

def test(a):
    print('TEST: ' + str(a))

Now I want to run this runction on a periodic basis. I use the schedule package.

def run_bot():
    time1 = str(gen_rand_time(18,19))
    print(time1)
    schedule.every(1).days.at(time1).do(test('TEST WORKED'))
    while True:
        schedule.run_pending()
        time.sleep(1)
run_bot()

when I run run_bot() and put in a time in the immediate future (say, 1 minute into the future), the test() function returns "TEST: TEST WORKED" without waiting for the specified random time.

Upvotes: 0

Views: 224

Answers (1)

You should probably try ... do(test,'TEST WORKED') instead of ... do(test('TEST WORKED')), see this.

Besides, it seems that you cannot use the same value for low and high (I wonder if you actually tried what you posted).

Upvotes: 1

Related Questions