今回は、Pythonで特定の時間を待つ方法について見ていきます。
これは、特定のイベントやタスクが特定の期間の後にスケジュールされている場合に特に重要です。
Pythonはこれを行うためのさまざまな方法を提供しています。
Python – シングルスレッド環境で特定の時間を待つ
もしあなたのメインプログラムがシングルスレッド/プログラムだけで構成されているなら、Pythonはこれをとても簡単にしてくれます。
Python でプログラムを特定の時間だけ待たせる方法として、time モジュールを使用する方法があります。
time.sleep()を使って待つ
time.sleep(n)を使って、n秒間待つことができます。
もちろん、より正確な時間間隔を指定するためにn` を 10 進数にすることもできます。
以下は簡単な例で、2つの関数を3秒間隔で呼び出す例です。
import time
def fun1(a):
return 2 * a
def fun2(a):
return a * a
if __name__ == '__main__':
inp = 10
print(f"Input = {inp}")
print(f"Result of fun1 call: {fun1(inp)}")
time.sleep(3) # Wait for 3 seconds
print(f"After 3 milliseconds, Result of fun2 call: {fun2(inp)}")
|
結果は以下の通りです。
Input = 10Result of fun1 call: 20After 3 seconds, Result of fun2 call: 100 |
十分シンプルでしょう?
この記事もチェック:Pythonのtime.sleepメソッドを使って一定時間だけ処理を止める方法
マルチスレッド環境での待ち時間
プログラム中に複数のスレッドがある場合でも、 time.sleep() を使って Python で特定のスレッドを特定の時間だけ待たせるのと同じロジックを使うことができます。
ここでは、3つのスレッドを生成し、交互に1秒間スリープさせ、他のスレッドは1からの数字を表示し続けるという例を示します。
ここでは、 concurrent.futures モジュールを使用して、 ThreadPoolExecutor でスレッドをプールして実行し、 as_completed() で結果を取得することにします。
スレッドを使った生成と取得の基本的な仕組みは以下の通りです。
from concurrent.futures import ThreadPoolExecutor, as_completed
# The threads will call this functiondef callback():
pass
with ThreadPoolExecutor() as thread_executor: # Await all results
await_results = [thread_executor.submit(callback) for i in range(1, tid+1)]
# Fetch them!
for f in as_completed([future for future in await_results]):
print(f.result())
|
では、メインプログラムのコードを書いてみましょう。
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
# Global Variable for the Thread ID Numbertid = 0
# Spawn 4 threadsNUM_THREADS = 4
def func(arg):
time.sleep(1)
return arg * arg
if __name__ == '__main__':
with ThreadPoolExecutor() as thread_executor:
start_time = time.time()
# Going to spawn threads
tid += NUM_THREADS
# Await all results
await_results = [thread_executor.submit(func, arg=i) for i in range(1, tid+1)]
for f in as_completed([future for future in await_results]):
print(f.result())
end_time = time.time()
print(f"Total Time taken for {NUM_THREADS} threads: {end_time - start_time}")
|
結果は以下の通りです。
14916Total Time taken for 4 threads: 1.0037879943847656 |
見ての通り、4つのスレッドが生成され、それらはすべて関数の結果を出す前に1秒間待機した。
threading.Timer() を使って関数の呼び出しを予約する
しかし、Python で特定の関数を特定の時間だけ待たせたい場合は、threading モジュールの threading.Timer() メソッドを使用します。
ここでは、5秒ごとに関数呼び出しをスケジュールする簡単な例を紹介します。
from threading import Timer
import time
def func(a, b):
print("Called function")
return a * b
# Schedule a timer for 5 seconds# We pass arguments 3 and 4t = Timer(5.0, func, [3, 4])
start_time = time.time()
# Start the timert.start()end_time = time.time()
if end_time - start_time < 5.0:
print("Timer will wait for sometime before calling the function")
else:
print("5 seconds already passed. Timer finished calling func()")
|
結果は以下の通りです。
Timer will wait for sometime before calling the functionCalled function |
ここでは、メインプログラムが5秒経過する前に最終行まで来てしまったので、Timerはプログラムが func() を呼び出すまで待たせています。
func(a, b)`を呼び出した後は、他に実行するものがないので、プログラムを終了させます。
また、この関数の戻り値はメインプログラムでは使用できないことに注意してください。
うまくいけば、これでスケジューリングとインターバル待ちに関するいくつかのアイデアを得ることができました。
この記事もチェック:Pythonのstatisticsモジュールで便利なメソッドを7つ紹介する
まとめ
今回は、Pythonでtime.sleep()`を使って特定の時間だけ待つということを学びました。
また、Multi-Threaded環境での使い方や、関数呼び出しのスケジューリングについても学びました。