每天在随机时间运行Python计划

每天在随机时间运行Python计划,python,scheduler,Python,Scheduler,如何从今天开始每天在随机时间运行计划作业?我想使用计划包 pip安装计划 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 {}&quo

如何从今天开始每天在随机时间运行计划作业?我想使用
计划

pip安装计划

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

通过在while循环中放置随机时间生成器,您提供了一个移动目标。具体来说,在查看源代码后,很明显,只有当
datetime.datetime.now()>=self.next\u run
为true时,作业才会运行(请参见
scheduler.run\u pending()
job.should\u run()
定义)。因为您总是在移动
作业。下一次运行
,只有在循环的特定迭代中碰巧遇到它时,您才会点击它。有趣的是,我认为这会导致一个bug,当您接近24:00时,实际运行您的作业的概率会增加,尽管这还没有显示出来。我认为您需要创建一个单独的函数来生成下一个随机时间,并从您的job函数调用它。例如:

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

如果您使用的是unix操作系统,并且在其中设置了随机时间,那么您可以使用?需要同时在Windows和Linux上运行,我希望所有逻辑都在一个软件包中。什么是“旋转”?while循环是无限的,并且
调度。run_pending()
不保持执行。需要while循环的不断迭代。它本质上是检查当前时间是否大于或等于每次迭代的最后一个计划作业。要真正检查脚本,您必须等待作业运行。出于这个原因,你可能想用更短的时间来练习。此外,您可能希望在while循环中放入一个
time.sleep
语句,该语句按作业频率的顺序排列,以最小化开销。