I have a function and i need to run it after 3 days using python
def hello()
print("hello world")
The script will be running,How to print it every 3 days in python
I have a function and i need to run it after 3 days using python
def hello()
print("hello world")
The script will be running,How to print it every 3 days in python
As @Nuts said in a comment, cron
is the best option if you want to run an entire program every three days. However, if you're running a microservice or something and just want one particular method to execute every three days, you can use timers.
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()
Just call make_thread()
once to execute hello()
the first time, and then it will call itself every three days (with a few seconds of margin for error, most likely), so long as the program remains running.
If you have to use python, one possible way (adapted slightly from this thread which has other good information) is to use a massive sleep statement.
#!/usr/bin/python3
import time
def hello():
print("Hello, World")
while True:
hello()
time.sleep(3*24*60*60)
Here is a more complete code snippet. I tested it for shorter intervals (not 3 days) but it should probably work
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()