i have this code:
scheduler.add_job(id='my_job1',
func=my_job,
trigger='cron',
second=str(random.randint(1,59)),
minute='*',
hour='*',
args=[app])
scheduler.init_app(app)
scheduler.start()
the code runs every min,but when it chooses random second for the first time it won't change it , for example if it selects to run at second 10 for first time then it runs at second 10 every time , i need it to be random
A workaround is to decorate your function:
import time
import random
def add_random_sleep(func):
"""
Decorator to add a random sleep (0-59 seconds) before calling the decorated function.
"""
def wrapper(*args, **kwargs):
time.sleep(random.randint(0, 59)) # you might want 0,59 since it's inclusive
return func(*args, **kwargs)
return wrapper
# later in your code
scheduler.add_job(id='my_job1',
func=add_random_sleep(my_job),
trigger='cron',
second=..., # whatever you need for it to be 0 seconds
minute='*',
hour='*',
args=[app])
You normally would decorate your function when defining it like this:
@add_random_sleep
def my_job(...):
...
but in this case that doesn't make sense since this behaviour is specific to your function being run as a CRON job. So instead we do add_random_sleep(my_job)