謝辞: 次のWebページに記載のソースコードを変更の上、掲載している.
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
Python のまとめ: 別ページ »にまとめ
Python の公式ページ: https://www.python.org/
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 プログラムの実行
次のことは、先ほどと同じ
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()