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()

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

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)
thank you, realized this myself after walking away and thinking about it for a second. Still a noob here...thx!
@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.
I was more making a comment about Thread in general doing that (see this question for example). But as I said, I don't think it's an issue here, I just wanted to make a precision :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.