2017-01-28 7 views
1

ディレクトリにファイルが作成されたことを検出する簡単なプログラムがあります。新しいファイルがある場合は毎分確認し、新しいファイルがない場合はタイマーをリセットすることになっています。ディレクトリ内のファイルなしで実行するとタイマーがリセットされない

import os 
import threading 
import time 
import sys 

def detector(): 
    filenames = os.listdir('/home/username/Documents/') 
    if filenames: 
     for i in filenames: 
      #do things 
    print('I started a thread!') 
    sys.stdout.flush() 
    threading.Thread(target=start_timer).start() 
def start_timer(): 
    print('I started a threaded timer at', t.ctime()) 
    sys.stdout.flush() 
    threading.Timer(60, detector) 
#UI stuff here 

、スクリプトは単に出力します:

I started a thread! 
I started a timer at [insert time here] 

しかし、一度だけ。私のスレッディングには何か問題があると思います(以前はスレッディングを使ったことがない)。スレッドが必要かどうかわかりませんが、タイマーはタイマーが完了するまでUIがハングするため、プログラムは通常のタイマーを待つことができません。 Timerだけ(あなたが最初のパラメータとして指定した秒数後に)一度そのコールバックを呼び出して、私たちが作成した理由であると

import os 
import threading 


def list_dir(my_dir, secs): 

    filenames = os.listdir(my_dir) 
    # print(filenames) 

    # Do your stuff here!!! 

    # Setting a new timer: call list_dir in secs seconds 
    threading.Timer(secs, list_dir, args=[my_dir, secs]).start() 

def start_timer(): 
    print('timer started!') 
    seconds = 60 # 60 seconds 
    directory = "/my/beloved/dir" # insert here the directory 
    threading.Timer(seconds, list_dir, args=[directory, seconds]).start() 


start_timer() 

は注意:ここで

+0

'detector'の最後に作成されたスレッドのターゲットを' start_timer'に設定し、 'Timer'のコールバックを' detector'に設定することで、何を達成したいですか?ところで、 'Timer'は' Thread'のサブクラスなので、それを開始するには、理論的に 'start'を呼び出さなければなりません... – nbro

+0

ああ...ええと...開始...私はタイマーを使用して、UIがハングしないでファイルが作成されたかどうかを確認します。 – Steampunkery

+0

マルチスレッドは簡単なプログラミング作業ではありません。あなたはまず基本を理解する必要があります... – nbro

答えて

1

は、私はあなたが欲しい何を考えての簡単な例ですlist_dirの中に別のTimerを入れてください。

+0

私は朝にそれをテストします。しかし、重要なことは次のとおりです:タイマーはプログラムが終了するまで停止しますか?(例:理論上のUIボタンはまだ機能しますか?)EDIT:午前中に答えを確認したら、その答えを受け入れます。 – Steampunkery

関連する問題