dbader / schedule

Python job scheduling for humans.
https://schedule.readthedocs.io/
MIT License
11.73k stars 959 forks source link

Schedule random time not working. #522

Closed thomasrgrant closed 2 years ago

thomasrgrant commented 2 years ago
schedule.every(5).to(10).seconds.do(job)

I want to change the random time it runs the schedule.

myruntime = schedule.every(5).to(10).seconds.do(job)

And I want to find out what that time will be.

sleeptime .interval
print(sleeptime .interval)

cnt = 0
sleeptime = 0

def job():
    global cnt
    cnt = cnt+1
    print(cnt)
    print(sleeptime)

sleeptime = schedule.every(5).to(10).seconds.do(job)
print(sleeptime.interval)

while True:
    schedule.run_pending()
    time.sleep(1)

However, the schedule.every(5).to(10).seconds.do(job) does not change at all. It stays at whatever value it selects. And never ever changes. Is there a solution to this? Or is it just a bug?

SijmenHuizenga commented 2 years ago

Hi @thomasrgrant, the .interval value returns the interval without the randomness. So in your example it always returns 5 because that's what has been passed to .to(). Use .next_run or last_run to see the timestamps including randomness:

import schedule, time

count = 0
job = None

def act():
    global count, job
    count = count+1
    print("count: ", count)
    print("next_run", job.next_run)

job = schedule.every(5).to(10).seconds.do(act)

while True:
    schedule.run_pending()
    time.sleep(1)

Output:

count:  1
next_run 2022-04-16 10:28:27.949641
count:  2
next_run 2022-04-16 10:28:32.957883
count:  3
next_run 2022-04-16 10:28:38.966738
count:  4
next_run 2022-04-16 10:28:48.975485
count:  5
next_run 2022-04-16 10:28:53.991683
count:  6
next_run 2022-04-16 10:29:03.001932
count:  7
next_run 2022-04-16 10:29:12.015057