包含Python的线程计时器

时间:2016-07-03 17:46:19

标签: python multithreading

我一直在阅读线程并尝试将其应用到我的代码中,但我不确定我这样做的方式是否是最佳做法。

我的代码只是导入一个自编脚本程序包,它会提取天气数据并在此后每隔60秒运行一次程序包。

我计划运行多个包,这些包一次收集数据,当时我已经找到了一个好的代码技术。

from package.weather import weatherapi
import threading

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

update()
  1. 首先它看起来很混乱,如果我想在一个线程中运行更多的包,我需要创建另一个更新函数
  2. 其次我无法杀死我的进程
  3. 如果有人有任何建议,我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

这对Threading.timer的使用非常糟糕。当你只是想要一个线程定期做某事时,你会不断开始新的线程。此代码是等效的:

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

由于线程都使用相同的命名空间,因此您也可以只使用一个函数。

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)

请注意,当线程已在运行时,也可以附加UPDATE_CALLABLES

答案 1 :(得分:0)

像这样的课做你想要的:

import threading

class Interval:
    def __init__(self):
        self.api=[]
        self.interval=60
        self.timer=self

    def set_api(self,api):
        self.api=api
    def set_interval(self,interval):
        self.interval=interval
    def cancel(self):
        pass
    def stop(self):
        self.timer.cancel()

    def update(self):
        for api in self.api:
            api()
        self.timer = threading.Timer(self.interval,self.update).start()

# Create instance and start with default parameters
interval=Interval()
interval.update()

# Later on change the list of items to call
interval.set_api([thisApi,thatApi])

# Later on still change the interval between calls
interval.set_interval(30)

# When you have had enough, cancel the timer
interval.stop()

请注意,它仍会为每个间隔时间创建一个新线程,但您可以随时更改所做的呼叫列表,并随时停止重复。

相关问题