每小时随机运行一次 Flask 调度程序

问题描述 投票:0回答:1

我有这个代码:

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()

代码每分钟运行一次,但是当它第一次选择随机秒时,它不会改变它,例如,如果它第一次选择在第10秒运行,那么它每次都在第10秒运行,我需要它随机

python flask
1个回答
0
投票

解决方法是装饰你的函数:

import time
import random


def add_random_sleep(func):
    """
    Decorator to add a random sleep (1-60 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])

© www.soinside.com 2019 - 2024. All rights reserved.