File: heartbeats.py

package info (click to toggle)
python-socketio-client 0.7.2-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 212 kB
  • sloc: python: 1,250; javascript: 142; makefile: 8
file content (52 lines) | stat: -rw-r--r-- 1,484 bytes parent folder | download | duplicates (4)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import logging
from threading import Thread, Event

from .exceptions import ConnectionError, TimeoutError


class HeartbeatThread(Thread):

    daemon = True

    def __init__(
            self, send_heartbeat,
            relax_interval_in_seconds,
            hurry_interval_in_seconds):
        super(HeartbeatThread, self).__init__()
        self._send_heartbeat = send_heartbeat
        self._relax_interval_in_seconds = relax_interval_in_seconds
        self._hurry_interval_in_seconds = hurry_interval_in_seconds
        self._adrenaline = Event()
        self._rest = Event()
        self._halt = Event()

    def run(self):
        try:
            while not self._halt.is_set():
                try:
                    self._send_heartbeat()
                except TimeoutError:
                    pass
                if self._adrenaline.is_set():
                    interval_in_seconds = self._hurry_interval_in_seconds
                else:
                    interval_in_seconds = self._relax_interval_in_seconds
                self._rest.wait(interval_in_seconds)
        except ConnectionError:
            logging.debug('[heartbeat connection error]')

    def relax(self):
        self._adrenaline.clear()

    def hurry(self):
        self._adrenaline.set()
        self._rest.set()
        self._rest.clear()

    @property
    def hurried(self):
        return self._adrenaline.is_set()

    def halt(self):
        self._rest.set()
        self._halt.set()