ディレクトリにファイルが作成されたことを検出する簡単なプログラムがあります。新しいファイルがある場合は毎分確認し、新しいファイルがない場合はタイマーをリセットすることになっています。ディレクトリ内のファイルなしで実行するとタイマーがリセットされない
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()
は注意:ここで
'detector'の最後に作成されたスレッドのターゲットを' start_timer'に設定し、 'Timer'のコールバックを' detector'に設定することで、何を達成したいですか?ところで、 'Timer'は' Thread'のサブクラスなので、それを開始するには、理論的に 'start'を呼び出さなければなりません... – nbro
ああ...ええと...開始...私はタイマーを使用して、UIがハングしないでファイルが作成されたかどうかを確認します。 – Steampunkery
マルチスレッドは簡単なプログラミング作業ではありません。あなたはまず基本を理解する必要があります... – nbro