【问题标题】:How to schedule a task in Python each week day every n seconds如何在 Python 中的每个工作日每隔 n 秒安排一次任务
【发布时间】:2019-12-27 15:58:26
【问题描述】:

我希望我的 Python 代码在每个工作日(周一到周五)而不是在周末(周六和周日)执行一个函数

有没有一种简单的方法可以使用调度库来实现这一点?

到目前为止,我已经设法每天每 10 秒执行一次该功能。但这也会在周六和周日执行

def helloWorld():
    print("Hello World!!!")


schedule.every(10).days.seconds.do(helloWorld)
while True:
    schedule.run_pending()
    time.sleep(1)

【问题讨论】:

  • 您是否尝试过 cron 作业?不过,最大频率为 1 分钟。
  • 我还没有尝试过 cron 作业,我会改为研究它。 1分钟完全没问题
  • 你也可以考虑systemctl systemdcalendar events

标签: python schedule


【解决方案1】:

你可以做一个 if 语句来检查工作日(星期一是 0):

if datetime.datetime.now().weekday() < 5:
    do_something()

我同意 Ankit 的观点,即 cron 作业可能更稳定。

【讨论】:

    【解决方案2】:

    一种方法是替换你的

    .days 与 .monday 到 .friday

    这样,您可以安排 5 项在周一至周五运行的任务,而所有 5 项工作在其他所有日子都不会执行任何操作。

    以星期一而不是几天的一些示例作为参考 https://schedule.readthedocs.io/en/stable/

    【讨论】:

    • 我已经厌倦了,但不幸的是,它会导致一个错误,要求将“星期一”更改为“星期一”。当我将其更改为“星期一”时,它会导致 AttributeError
    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2017-11-17
    • 2015-11-22
    相关资源
    最近更新 更多