def heartbeat(queue_name, task_id, owner, message, index):
    """Sets the heartbeat status of the task and extends its lease.

    The task's lease is extended by the same amount as its last lease to
    ensure that any operations following the heartbeat will still hold the
    lock for the original lock period.

    Args:
        queue_name: Name of the queue the work item is on.
        task_id: ID of the task that is finished.
        owner: Who or what has the current lease on the task.
        message: Message to report as the task's current status.
        index: Number of this message in the sequence of messages from the
            current task owner, starting at zero. This lets the API receive
            heartbeats out of order, yet ensure that the most recent message
            is actually saved to the database. This requires the owner issuing
            heartbeat messages to issue heartbeat indexes sequentially.

    Returns:
        True if the heartbeat message was set, False if it is lower than the
        current heartbeat index.

    Raises:
        TaskDoesNotExistError if the task does not exist.
        LeaseExpiredError if the lease is no longer active.
        NotOwnerError if the specified owner no longer owns the task.
    """
    task = _get_task_with_policy(queue_name, task_id, owner)
    if task.heartbeat_number > index:
        return False

    task.heartbeat = message
    task.heartbeat_number = index

    # Extend the lease by the time of the last lease.
    now = datetime.datetime.utcnow()
    timeout_delta = task.eta - task.last_lease
    task.eta = now + timeout_delta
    task.last_lease = now

    db.session.add(task)

    signals.task_updated.send(app, task=task)

    return True
Sets the heartbeat status of the task and extends its lease.

    The task's lease is extended by the same amount as its last lease to
    ensure that any operations following the heartbeat will still hold the
    lock for the original lock period.

    Args:
        queue_name: Name of the queue the work item is on.
        task_id: ID of the task that is finished.
        owner: Who or what has the current lease on the task.
        message: Message to report as the task's current status.
        index: Number of this message in the sequence of messages from the
            current task owner, starting at zero. This lets the API receive
            heartbeats out of order, yet ensure that the most recent message
            is actually saved to the database. This requires the owner issuing
            heartbeat messages to issue heartbeat indexes sequentially.

    Returns:
        True if the heartbeat message was set, False if it is lower than the
        current heartbeat index.

    Raises:
        TaskDoesNotExistError if the task does not exist.
        LeaseExpiredError if the lease is no longer active.
        NotOwnerError if the specified owner no longer owns the task.