File size: 1,030 Bytes
45f43d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from __future__ import annotations

import threading
import time

from .service import SanctuaryService


class SanctuaryRuntime:
    def __init__(self, service: SanctuaryService, interval_s: float = 3.0) -> None:
        self.service = service
        self.interval_s = max(0.25, interval_s)
        self.running = False
        self._thread: threading.Thread | None = None

    def start(self) -> None:
        if self.running:
            return
        self.running = True
        self._thread = threading.Thread(target=self._loop, daemon=True, name="sanctuary-runtime")
        self._thread.start()

    def stop(self) -> None:
        self.running = False
        if self._thread is not None:
            self._thread.join(timeout=2.0)
            self._thread = None

    def _loop(self) -> None:
        while self.running:
            started = time.perf_counter()
            self.service.background_pulse()
            elapsed = time.perf_counter() - started
            time.sleep(max(0.0, self.interval_s - elapsed))