0

I'm trying to print an updated value and store it in a CSV file. Im using threading and the print would be every 1 second, however after every second that ellapses its the same value that is printed. Can someone help?

import urllib.request, urllib.parse, urllib.error
import json
import threading
import time

localtime = time.asctime( time.localtime(time.time()))



url = 'api'

uh = urllib.request.urlopen(url)
data = uh.read().decode()

js =json.loads(data)


def last_price():
  threading.Timer(1.0, last_price).start()
  print(js['last'])
  print(localtime)


last_price()
BorangeOrange1337
  • 182
  • 1
  • 1
  • 20

1 Answers1

1

The variable js is currently evaluated only once. If you want to query the API every second, move the query code inside the function being executed by the timer:

url = 'api'

def last_price():
    localtime = time.asctime( time.localtime(time.time()))
    uh = urllib.request.urlopen(url)
    data = uh.read().decode()
    js = json.loads(data)
    print(js['last'])
    print(localtime)
    threading.Timer(1.0, last_price).start()

last_price()
Egal
  • 1,374
  • 12
  • 22
  • This is a good way of doing it, but since it takes some time for Python to execute all the code inside the function, it will technically be a bit more than a minute... (which I wouldn't say is an issue) – Arthur Spoon Jul 31 '17 at 00:30
  • thank you, realized this myself after walking away and thinking about it for a second. Still a noob here...thx! – BorangeOrange1337 Jul 31 '17 at 00:38
  • @ArthurSpoon you're correct, but if you fire the timer at the beginning you're risking spawning many threads if, for example, the API is unresponsive and blocks you for a long time. Handling that will be an unnecessary overhead if millisecond precision is not of high priority. – Egal Jul 31 '17 at 00:39
  • I was more making a comment about `Thread` in general doing that (see [this question](https://stackoverflow.com/questions/45384065/is-there-a-way-to-stop-timer-creep/45384212#45384212) for example). But as I said, I don't think it's an issue here, I just wanted to make a precision :) – Arthur Spoon Jul 31 '17 at 00:44