金子邦彦研究室プログラミングPython一定間隔で処理の繰り返し

一定間隔で処理の繰り返し

謝辞: 次のWebページに記載のソースコードを変更の上、掲載している.

https://qiita.com/miminashi/items/50a4f0906ab8f18b105d

前準備

Python の準備(Windows,Ubuntu 上)

サイト内の関連ページ

関連する外部ページ

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 プログラムの実行

[image]

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」)

[image]

上と同じ機能だが、別の書き方

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()

[image]