【发布时间】:2019-01-13 09:08:21
【问题描述】:
我有一个函数,我需要在 3 天后使用 python 运行它
def hello()
print("hello world")
脚本将运行,如何在python中每3天打印一次
【问题讨论】:
-
您可以为此使用 cron 作业:*.com/questions/11774925/…
标签: python
我有一个函数,我需要在 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(),然后它会每三天调用一次(很可能会有几秒钟的错误余量),只要程序保持运行。
【讨论】:
如果你必须使用 python,一种可能的方法(稍微改编自 this 线程,它有其他好的信息)是使用大量的睡眠语句。
#!/usr/bin/python3
import time
def hello():
print("Hello, World")
while True:
hello()
time.sleep(3*24*60*60)
这里有一个更完整的代码sn-p。我测试了较短的时间间隔(不是 3 天),但它应该可以工作
import numpy as np
import time
import datetime
def function_to_call_periodically():
print("Hello World")
# specify the interval and the time (3 days and at 11h00)
# The code below assumes the interval is more than a day
desired_time_delta_in_seconds = 3*24*60*60 # 3 days
desired_time_minutes = 00
desired_time_hours = 11
# set the starting time the code will run every 3 days from this date (at the specified time)
start_date = datetime.datetime(2018, 8, 7) # year, month date (hours, minutes, seconds will all be zero)
start_stamp = start_date.timestamp()
# if the scripts gets restarted we need to figure out when the next scheduled function call is
# so we need to nkow when we started
curr_time = datetime.datetime.now()
curr_stamp = curr_time.timestamp()
last_interval = (curr_stamp - start_stamp) // desired_time_delta_in_seconds
# Loop forever
while(True):
# sleep so we don't use up all the servers processing power just checking the time
time.sleep(5)
# get the current time and see how many whole intervals have elapsed
curr_time = datetime.datetime.now()
curr_stamp = curr_time.timestamp()
num_intervals = (curr_stamp - start_stamp) // desired_time_delta_in_seconds # python 3 integer division
# if at least another interval has elapsed and it is currently the time for the next call
# then call the function and update the interval count so we don't call it again
if (num_intervals > last_interval) and (curr_time.hour >= desired_time_hours) and (curr_time.minute >= desired_time_minutes):
print("Calling scheduled function at ", curr_time)
last_interval = num_intervals
function_to_call_periodically()
【讨论】: