2016-07-03 7 views
1

私はスレッディングを読んで、コードに実装しようとしましたが、私がやっている方法がベストプラクティスかどうかは分かりません。Python Threading timer with package

私のコードは気象データを取得し、その後60秒ごとにパッケージを実行する自己スクリプトパッケージをインポートするだけです。

良いコード手法を試してみると、すぐにデータを収集する複数のパッケージを実行する予定です。

from package.weather import weatherapi 
import threading 

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

update() 
  1. まず第二に、私は
私のプロセスを殺すことができないんだけど、それだけで厄介なようだと、私はスレッドで実行されている以上のパッケージを望んでいた場合、私は別の更新機能
  • を作成する必要があるだろう

    誰かが何か提案があれば、大変感謝しています。

  • +0

    遅延に 'time.sleep'を使用してみませんか?すべてのスレッドを終了せずにプロセスを終了したい場合は、起動する前に 'daemon'フラグを' True'に設定してください。 – MisterMiyagi

    +0

    こちらもご覧ください:http://stackoverflow.com/q/3393612/1025391 – moooeeeep

    答えて

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

    スレッドはすべて同じ名前空間を使用するため、1つの関数で行うこともできます。

    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は、スレッドがすでに実行されている間に追加することもできます。

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

    注意をしていますが、任意の時点で行われたコールのリストを変更しての繰り返し、それを停止することができますどんなときも。