duty-board-dog/timeout.py

44 lines
1.2 KiB
Python

# SPDX-FileCopyrightText: 2023 Egor Guslyancev <electromagneticcyclone@disroot.org>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"The module provides class to check timeouts."
import time
import typing
class Timeout:
"Timeout checking. Period in seconds."
__timeout = None
__caution = True
def __init__(self, period: int):
self.period = period
@property
def period(self) -> int:
"Period property."
return self.__period
@period.setter
def period(self, period: int):
self.__period = period
def check(self, once_func: typing.Callable, always_func: typing.Callable) -> bool:
"""
Check if time is out.
`once_func` called once if time is not out, but `check` called twice.
`always_func` called when `check` called twice or more.
"""
if self.__timeout is not None:
if time.time() - self.__timeout < self.period:
if self.__caution:
once_func()
self.__caution = False
always_func()
return True
self.__caution = True
self.__timeout = time.time()
return False