【问题标题】:Running Python schedule daily at random times每天随机运行 Python 计划
【发布时间】:2020-10-23 08:53:41
【问题描述】:

如何从今天开始每天随机运行计划作业?我想使用schedule 包。

pip install schedule

import schedule

def job()
   print("foo")
   return schedule.CancelJob

while True:
   time_str = '{:02d}:{:02d}'.format(random.randint(6, 10), random.randint(0, 59))
   print("Scheduled for {}".format(time_str))
   schedule.every().day.at(time_str).do(job)
   schedule.run_pending()

上面的代码只是旋转:

Scheduled for 06:36
Scheduled for 10:00
Scheduled for 06:18

【问题讨论】:

  • 如果您使用的是 unix 操作系统并通过那里设置随机时间,您也许可以使用 crontab
  • 需要在 Windows 和 Linux 上运行,我希望所有逻辑都在一个包中。

标签: python scheduler


【解决方案1】:

通过将随机时间生成器放入 while 循环中,您可以提供移动目标。具体来说,在查看源代码here 之后,很明显只有当datetime.datetime.now() >= self.next_run 为真时,作业才会运行(参见scheduler.run_pending()job.should_run() 定义)。因为您总是在移动job.next_run,所以只有在循环的特定迭代中它恰好在过去时,您才会点击它。有趣的是,我认为这会导致一个错误,即当您接近 24:00 时,实际运行您的工作的可能性会增加,尽管这尚未显示。我认为您需要创建一个单独的函数来生成下一个随机时间,并从您的工作职能中调用它。例如:

import schedule
import time
import random

def job():
   print("foo")
   schedule_next_run()
   return schedule.CancelJob

def schedule_next_run():
   time_str = '{:02d}:{:02d}'.format(random.randint(6, 10), random.randint(0, 59))
   schedule.clear()
   print("Scheduled for {}".format(time_str))
   schedule.every().day.at(time_str).do(job)

schedule_next_run()

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

请注意,该示例在作业开始的那一天可能不是随机的,因为您的随机时间可能在您碰巧开始脚本的时间之前。您可以在未来的第一天随机选择一个时间,以根据需要规避这种情况。

为了验证上面的例子,我使用了更短的时间跨度。以下对我有用:

import schedule
import time
import random

def job():
   print("foo")
   schedule_next_run()
   return schedule.CancelJob

def schedule_next_run():
   time_span = random.randint(1, 5)
   schedule.clear()
   print(f'Scheduled in {time_span} seconds')
   schedule.every(time_span).seconds.do(job)

schedule_next_run()

while True:
   schedule.run_pending()

【讨论】:

  • “旋转”是什么意思? while 循环是无限的,schedule.run_pending() 不会执行。预期 while 循环的不断迭代。它本质上是检查当前时间是否大于或等于每次迭代的最后一个计划作业。
  • 要真正检查脚本,您必须等待您的作业运行。因此,您可能希望以更短的时间跨度进行练习。此外,您可能希望将 time.sleep 语句放在按作业频率顺序排列的 while 循环中,以最大限度地减少开销。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
相关资源
最近更新 更多