mustrequiredlife mustrequiredlife - 5 months ago 26
Python Question

Python Threading timer with package

I've been reading up on threading and tried implementing it into my code however I'm not sure if the way I'm doing it, is the best practise.

My code simply imports a self scripted package which pulls weather data and runs the package every 60 seconds thereafter.

I plan on running multiple packages which gather data at once, when I have worked out a good code technique.

from package.weather import weatherapi
import threading

def update():
weatherapi()
threading.Timer(60, update).start()

update()



  1. Firstly it just seems messy and if I wanted more packages running in a thread, I'd need to create another update function

  2. Secondly I'm not able to kill my process



If anyone has any suggestions, it would be greatly appreciated.

Answer

This is a really bad use of Threading.timer. You're constantly starting new threads, when you just want one thread to do something regularly. This code is equivalent:

from package.weather import weatherapi
import threading
import time

def update():
  while True:
    weatherapi()
    time.sleep(60)

WHEATHER_THREAD=threading.Thread(target=update)
WHEATHER_THREAD.daemon = True  # main can exit while thread is still running
WHEATHER_THREAD.start()

Since threads all use the same namespace, you can also make do with just one function.

UPDATE_CALLABLES = [weatherapi]  # add new functions to have them called by update
def update():
  while True:
    for func in UPDATE_CALLABLES:
      func()
    time.sleep(60)

Note that UPDATE_CALLABLES can also be appended while the Thread is already running.

Comments