0
1

More than 3 years have passed since last update.

python3で定期的に関数を実行する高階関数

Last updated at Posted at 2020-06-02

6/2,3 しらかみゅさんのアドバイスにより、より短いコードでより正確な動きができるようになりました。

定期的に関数を実行する高階関数
def minute_interval(interval_min: int, at_sec: int, function, *args, **kwargs):
    """RUNS FUNCTION REPETITIVELY
    Args:
        interval_min(int) : Value of minute. If 11, it will operate at 00, 11, 22, 33, 44, and 55.
        at_sec(int) : Value of second. If 5, it will operate at 05.
        function: Function you want to call repetitively
    """
    while True:
        now = datetime.now()

        # when interval_min is 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, or 30
        if now.minute + interval_min < 60:
            wait_min = -now.minute % interval_min
        # when interval_min CANNOT divide 60. e.g: 7,8,9,11,13...
        else:
            wait_min = 60 - now.minute

        now_sec = now.second + (now.microsecond / 1000_000)
        wait_sec = ((wait_min * 60) + (at_sec - now_sec)) % (interval_min * 60)
        print(f'call func after {int(wait_sec/60)} min {wait_sec%60} sec')
        time.sleep(wait_sec)

        function(*args, **kwargs)
0
1
6

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
1