1

So I stumbled upon an answer that almost satisfies my question.

In my case I want to fetch the status of my limit buy order in market for 5 seconds every 0.8 seconds or so. The code that I found looks like this:

import threading

def printit():
  threading.Timer(0.8, printit).start()
  print("Hello, World!")

and to run something for 5 seconds, one can do the following:

import time
  t_end = time.time() + 5
  while time.time() < t_end:
    print('Hello World')

but combining those two like so, is not gonna work:

while time.time() < t_end:
  printit()

So I am just wondering how I can make printit() run every 0.8 seconds for 5 seconds?

Naz
  • 2,012
  • 1
  • 21
  • 45

2 Answers2

3

Here's a variation of your threading code. The benefit of using threading is that the whole program isn't frozen, so you can (for example) fetch some data from a URL while you're waiting, rather than having a fetch-sleep cycle.

import threading
import time

def printit(interval, endtime):
    now = time.time()
    if now < endtime:
        threading.Timer(interval, printit, args=[interval, endtime]).start()
        print("Hello", now - t_start)

t_start = time.time()

printit(0.8, t_start + 5)

typical output

Hello 4.458427429199219e-05
Hello 0.8010139465332031
Hello 1.6028234958648682
Hello 2.4049606323242188
Hello 3.205900192260742
Hello 4.0072197914123535
Hello 4.808593988418579
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1

Here you go! just put your function call where I am printing!

import time
totalTime = 5
dt = 0.0

while dt <= totalTime:
    print(dt)
    time.sleep(0.8)
    dt += 0.8
Tyler Cowan
  • 820
  • 4
  • 13
  • 35
  • Not a very robust solution, since `time.sleep` is not precise. This will almost assuredly take over 6 seconds to finish (especially because you're sleeping for another interval on the last time around). It's a great quick solution for a console app, though. – Adam Smith Jan 25 '18 at 17:31
  • @AdamSmith he did say "0.8 seconds or so" – Tyler Cowan Jan 25 '18 at 17:33
  • for reference https://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep – Tyler Cowan Jan 25 '18 at 17:34
  • 2
    @isquared-KeepitReal Note that `sleep` will put your whole program to sleep for (at least) the specified interval. That may be ok, but if you don't want that to happen then you should use threading. – PM 2Ring Jan 25 '18 at 17:39