def heartbeat(self):
try:<EOL><INDENT>with create_session() as session:<EOL><INDENT>job = session.query(BaseJob).filter_by(id=self.id).one()<EOL>make_transient(job)<EOL>session.commit()<EOL><DEDENT>if job.state == State.SHUTDOWN:<EOL><INDENT>self.kill()<EOL><DEDENT>is_unit_test = conf.getboolean('<STR_LIT>', '<STR_LIT>')<EOL>if not is_unit_test:<EOL><INDENT>sleep_for = <NUM_LIT:0><EOL>if job.latest_heartbeat:<EOL><INDENT>seconds_remaining = self.heartrate -(timezone.utcnow() - job.latest_heartbeat).total_seconds()<EOL>sleep_for = max(<NUM_LIT:0>, seconds_remaining)<EOL><DEDENT>sleep(sleep_for)<EOL><DEDENT>with create_session() as session:<EOL><INDENT>job = session.query(BaseJob).filter(BaseJob.id == self.id).first()<EOL>job.latest_heartbeat = timezone.utcnow()<EOL>session.merge(job)<EOL>session.commit()<EOL>self.heartbeat_callback(session=session)<EOL>self.log.debug('<STR_LIT>')<EOL><DEDENT><DEDENT>except OperationalError as e:<EOL><INDENT>self.log.error("<STR_LIT>", str(e))<EOL><DEDENT>
Heartbeats update the job's entry in the database with a timestamp
for the latest_heartbeat and allows for the job to be killed
externally. This allows at the system level to monitor what is
actually active.

For instance, an old heartbeat for SchedulerJob would mean something
is wrong.

This also allows for any job to be killed externally, regardless
of who is running it or on which machine it is running.

Note that if your heartbeat is set to 60 seconds and you call this
method after 10 seconds of processing since the last heartbeat, it
will sleep 50 seconds to complete the 60 seconds and keep a steady
heart rate. If you go over 60 seconds before calling it, it won't
sleep at all.