首页 > 解决方案 > 如何安排函数在第一次在 python 中运行后每 3 天运行一次

问题描述

我有一个函数,我需要在 3 天后使用 python 运行它

def hello()
print("hello world")

脚本将运行,如何在python中每3天打印一次

标签: python

解决方案


正如@Nuts 在评论中所说,cron如果您想每三天运行一次整个程序,这是最好的选择。但是,如果您正在运行微服务或其他东西,并且只想每三天执行一个特定方法,则可以使用计时器。

import threading

my_timer = None

def make_thread():
    # create timer to rerun this method in 3 days (in seconds)
    global my_timer
    my_timer = threading.Timer(259200, make_thread)
    # call hello function
    hello()

第一次只调用make_thread()一次hello(),然后它会每三天调用一次(很可能会有几秒钟的错误余量),只要程序保持运行。


推荐阅读