一定間隔で処理の繰り返し
謝辞: 次のWebページに記載のソースコードを変更の上、掲載している.
前準備
Python の準備(Windows,Ubuntu 上)
- Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール(winget を使用しないインストール): 別ページ »で説明
- Ubuntu では,システム Pythonを使うことができる.Python3 開発用ファイル,pip, setuptools のインストール: 別ページ »で説明
【サイト内の関連ページ】
- Python のまとめ: 別ページ »にまとめ
- Google Colaboratory の使い方など: 別ページ »で説明
【関連する外部ページ】 Python の公式ページ: https://www.python.org/
Python の公式ページ: https://www.python.org/
ソースコードの例と実行結果の例
- 「5秒」毎に処理を繰り返す.
- 「5秒」以内に処理が終わらなかったときは,さらに5秒待つ
import time
import threading
def worker():
print(time.gmtime())
time.sleep(8)
def mainloop(time_interval, f):
now = time.time()
while True:
t = threading.Thread(target=f)
t.setDaemon(True)
t.start()
t.join()
wait_time = time_interval - ( (time.time() - now) % time_interval )
time.sleep(wait_time)
mainloop(5, worker)
Python プログラムの実行

5秒毎に処理を繰り返す。別スレッドでその結果を表示
次のことは、先ほどと同じ
- 「5秒」毎に処理を繰り返す.
- 「5秒」以内に処理が終わらなかったときは,さらに5秒待つ
import time
import threading
c=0
c2=0
# ずっと動き続けるスレッド
def another():
global c
global c2
while True:
c = c + 1
print("hello, %d, %d" % (c, c2))
time.sleep(1)
# 定期的に繰り返すスレッド
def worker():
global c2
c2 = c2 + 1
print(time.gmtime())
time.sleep(8)
def mainloop(time_interval, f, another):
now = time.time()
t0 = threading.Thread(target=another)
t0.setDaemon(True)
t0.start()
while True:
t = threading.Thread(target=f)
t.setDaemon(True)
t.start()
t.join()
wait_time = time_interval - ( (time.time() - now) % time_interval )
time.sleep(wait_time)
if __name__ == '__main__':
mainloop(5, worker, another)
hoge.py のような名前で保存し、「python hoge.py」のようにして実行(Ubuntu の場合は「python3 hoge.py」)

上と同じ機能だが、別の書き方
import time
import threading
c=0
c2=0
# ずっと動き続ける処理
def another():
global c
global c2
while True:
c = c + 1
print("hello, %d, %d" % (c, c2))
time.sleep(1)
# 定期的に繰り返すスレッド
def worker():
print(time.gmtime())
time.sleep(8)
def mainloop():
time_interval = 5
now = time.time()
while True:
t = threading.Thread(target=worker)
t.setDaemon(True)
t.start()
t.join()
wait_time = time_interval - ( (time.time() - now) % time_interval )
time.sleep(wait_time)
if __name__ == '__main__':
t0 = threading.Thread(target=mainloop)
t0.setDaemon(True)
t0.start()
another()
