python - 如何在Python中安排定时事件

标签 python scheduler

我想在 python 中安排一个重复的定时事件,如下所示: “在时间 X 启动函数 Y(在单独的线程中)并每小时重复一次”

“X”是固定时间戳

代码应该是跨平台的,所以我想避免使用像“cron”这样的外部程序来执行此操作。

代码摘录:

    import threading
    threading.Timer(10*60, mail.check_mail).start()
    #... SET UP TIMED EVENTS HERE
    while(1):
        print("please enter command")
        try:
            command = raw_input()
        except:
            continue
        handle_command(command) 

最佳答案

创建 dateutil.rrule , rr 作为您的日程安排,然后在您的线程中使用如下循环:

for ts in rr:
    now = datetime.now()
    if ts < now:
        time.sleep((now - ts).total_seconds())
    # do stuff

或者更好的解决方案,可以考虑时钟变化:

ts = next(rr)
while True:
    now = datetime.now()
    if ts < now:
        time.sleep((now - ts).total_seconds() / 2)
        continue
    # do stuff
    ts = next(rr)

关于python - 如何在Python中安排定时事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10700500/

相关文章:

python - 使用 split 从文件中的一行读取特定字符串

PHP 随机团队日程生成器 - 循环调度程序

python - Django/Python requirements.txt 总是获取最近的包

python - 在python中高效处理大型二进制文件

python - scrapy : ERROR: Error downloading <GET http://stackoverflow. com/questions?sort=votes> TypeError: 'float' 对象不可迭代

C++常见的std::make_unique、std::packaged_task和std::promise问题

python - Airflow scheduler 是否有可能在开始下一天之前先完成前一天的周期?

c - 如何使用 swapcontext() 恢复函数的执行(而不是再次启动)?

带完成检查的java cron解决方案

Python Pandas Groupby/追加列