【问题标题】:Ignoring past events with python sched.py使用 python sched.py 忽略过去的事件
【发布时间】:2023-01-31 00:37:48
【问题描述】:

我想安排一系列绝对定时的事件,这些事件将在未知延迟后调用。这意味着在我们运行调度程序的那一刻,某些事件可能已经过去了。但是,在我的应用程序中,运行开始时的过期事件需要被丢弃。

是否有可能在 Python 的 sched.py 库中指示调度程序在我们运行调度程序的那一刻丢弃过去的事件?

例如,当运行这样一个简单的事件序列时:

import sched
import time


s = sched.scheduler(timefunc=time.time)

now = time.time()

s.enterabs(time=now-5,action=print,argument=(1,),priority=1)
s.enterabs(time=now+2,action=print,argument=(2,),priority=1)
s.enterabs(time=now+4,action=print,argument=(3,),priority=1)

s.run()

我想看到类似的东西:

2
3

但是,输出是:

1
2
3

因为调度程序会立即赶上过去的事件。我能以某种方式覆盖这种行为吗?或者是否有另一个图书馆可以更好地响应这一要求?

先感谢您

【问题讨论】:

    标签: python sched


    【解决方案1】:

    在schedule库中,可以在创建scheduler对象时通过设置jobstore参数来忽略过去的事件。 jobstore 参数确定计划作业的持久性。

    忽略过去事件的一种常见方法是使用内存中的作业存储,它只在程序的生命周期内存储作业。当程序重新启动时,作业将丢失,因此您不会看到任何过去的事件。

    以下是如何使用内存中作业存储创建调度程序对象的示例:

    import schedule
    import time
    
    def job():
        print("Job running!")
    
    # Create a scheduler object with an in-memory jobstore
    scheduler = schedule.Scheduler(jobstore="memory")
    
    # Schedule the job to run every minute
    scheduler.every(1).minutes.do(job)
    
    # Start the scheduler
    scheduler.start()
    
    # Keep the program running
    while True:
        scheduler.run_pending()
        time.sleep(1)
    

    使用此代码,作业函数将每分钟运行一次,过去的事件将被忽略,因为它们未存储在内存中的作业存储中。

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多