code: def __heartbeat_loop(self):
          
          log.info('Starting heartbeat loop')
          now = monotonic()
  
          # Setup the initial due time for the outbound heartbeat
          if self.send_sleep != 0:
              self.next_outbound_heartbeat = now + self.send_sleep
  
          while self.running:
              now = monotonic()
  
              next_events = []
              if self.next_outbound_heartbeat is not None:
                  next_events.append(self.next_outbound_heartbeat - now)
              if self.receive_sleep != 0:
                  t = self.received_heartbeat + self.receive_sleep - now
                  if t > 0:
                      next_events.append(t)
              sleep_time = min(next_events)
              if sleep_time > 0:
                  terminate = self.heartbeat_terminate_event.wait(sleep_time)
                  if terminate:
                      break
  
              now = monotonic()
  
              if not self.transport.is_connected():
                  time.sleep(self.send_sleep)
                  continue
  
              if self.send_sleep != 0 and now > self.next_outbound_heartbeat:
                  log.debug("Sending a heartbeat message at %s", now)
                  try:
                      self.transport.transmit(utils.Frame(None, {}, None))
                  except exception.NotConnectedException:
                      log.debug("Lost connection, unable to send heartbeat")
                  except Exception:
                      _, e, _ = sys.exc_info()
                      log.debug("Unable to send heartbeat, due to: %s", e)
  
              if self.receive_sleep != 0:
                  diff_receive = now - self.received_heartbeat
  
                  if diff_receive > self.receive_sleep:
                      # heartbeat timeout
                      log.warning("Heartbeat timeout: diff_receive=%s, time=%s, lastrec=%s",
                                  diff_receive, now, self.received_heartbeat)
                      self.transport.set_connected(False)
                      self.transport.disconnect_socket()
                      self.transport.stop()
                      for listener in self.transport.listeners.values():
                          listener.on_heartbeat_timeout()
          self.heartbeat_thread = None
          log.info('Heartbeat loop ended')
docs: Main loop for sending (and monitoring received) heartbeats.