'Exectue function every one hour in Python
I wanted to execute a program every once hour. I can use time.sleep function to delay the interval but, if the program executed let's say at 16:30 then the function will only execute at 17:30. But I need to execute the function at 17:00, 18:00 and so on.
import datetime
def onehour(value):
print "%d Hours" % value
now = datetime.datetime.now()
oncehour(now.hour)
Solution 1:[1]
You need to sleep first, if current time is 12:23, then you need to sleep 60-23 = 37 minutes and then run your code every hour.
Here you can write like this:
import time
import datetime
time.sleep(60 * (60 - datetime.datetime.now().minute))
while True:
do_smth()
sleep(60 * 60)
Solution 2:[2]
What about Cron jobs ? You can write your code inside a Python file then call it from command line inside your crontab:
0 * * * * python script.py
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Saksow |