0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WatchDogTimerを作る

Posted at

WatchDogTimerを作る

仕様

  • 日向で寛いでいる(という設定の)犬を撫でる!
  • 一定時間撫でられなかった犬は,次に撫でようとしたときに吠えてくる
  • 一度吠えた犬は二度と撫でさせてくれない

コード

watchdog.py
from threading import Event, Thread


class WatchdogBark(Exception):
    pass

class Watchdog(Thread):

    def __init__(self, interval):
        Thread.__init__(self)
        self.interval = interval
        self.watching = True
        self.petted = Event()
        self.bark = False

    def stop(self):
        self.watching = False

    def pet(self):
        if self.bark:
            raise WatchdogBark()
        self.petted.set()

    def run(self):
        while self.watching:
            self.petted.wait(self.interval)
            if not self.petted.is_set():
                self.bark = True
                break
            self.petted.clear()

使い方

watchdog_sample.py
import random
import time

from watchdog import Watchdog, WatchdogBark


def main():
    # 3秒ごとに撫でないと怒っちゃう犬
    dog = Watchdog(3)
    dog.start()

    try:
        for t in range(20):
            print()
            # なんか処理 (ここではランダム時間sleep)
            processing_time = random.random() * 4
            print(f"{t+1}番目の処理は{processing_time:.1f}秒かかりそう...")
            time.sleep(processing_time)
            print("犬を撫でる!")
            dog.pet()
            print("撫でても吠えられなかった!!")
    except WatchdogBark:
        print("吠えられた.")
    else:
        print("吠えられることなく処理しきれました.")
    finally:
        dog.stop()
        dog.join()

if __name__ == '__main__':
    main()

感想

この犬,永遠に放置しても撫でようとしなければ吠えてこないぞ!!!!
(自分から吠えるようにするにはsignal使った割り込みをしましょう.)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?