I need to write a Python code in order to repeat a trading algorithm exactly every fith minute of the hour. All the solutions that I tried as for example Sleep() will sum machine time, and this is not what I want.
I need to preserve state between calls, ... I want the algorithm to run exactly every 5 minutes (for example 14:00; 14:05; 14:10; 14:15......). The algorithm (retriving the data and cruncing the numbers) itself takes approximatly 12 seconds to be executed. If the computer is suspended I will skip the iteration.
EDIT
According to your comment: "I want the algorithm to run exactly every 5 minutes (for example 14:00; 14:05; 14:10; 14:15......)."
using datetime and infinite loop:
import time
import datetime
while True:
if datetime.datetime.now().minute % 5 == 0:
#do algorithm
time.sleep(60)
You could use a cron job for that if you work in a linux environment. Open the cron tab by
crontab -e
The following will start a python script cronjob.py every 5th minute of an hour:
5 * * * * python /path/to/script/cronjob.py
edit: since op specified "want the algorithm to run exactly every 5 minutes":
*/5 * * * * python /path/to/script/cronjob.py
import time
while True:
time.sleep(300 - time.time() % 300)
crunch_numbers()
crunch_numbers()
is called on 5 minute boundaries defined by time.time()
clock.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.