2

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Diego Di Tommaso
  • 155
  • 1
  • 2
  • 13
  • related: [What is the best way to repeatedly execute a function every x seconds in Python?](http://stackoverflow.com/a/25251804/4279) – jfs Mar 02 '16 at 20:36

3 Answers3

4

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)
mvelay
  • 1,520
  • 1
  • 10
  • 23
2
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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
1

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
meltdown90
  • 251
  • 1
  • 11
  • This could work but I have some variables that I need to store in the code and that I guess would get back to initiation state if I use this solution – Diego Di Tommaso Mar 02 '16 at 14:26
  • @DiegoDiTommaso: put this information (that you need "to preserve state between calls") into your question. Mention what do you want to happen if an iteration takes longer than 5 minutes (do you want to skip the next iteration or run two iterations concurrently?). What do you want to happen if the computer time jumps (forward/backwards), if is the computer is suspended -- do you want to skip the corresponding iterations? – jfs Mar 02 '16 at 20:41
  • it's not "every five minute" but "every 5th minute of the hour". – mvelay Mar 02 '16 at 21:32
  • Yes, I need to preserve state between calls, I'm sorry I was not clear in my first message, what I meant is that 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. Thanks! – Diego Di Tommaso Mar 03 '16 at 08:08