Cancels the job. Functions should check the #Job.cancelled flag from time
    to time to be able to abort pre-emptively if the job was cancelled instead
    of running forever.

def cancel(self):
    """
    Cancels the job. Functions should check the #Job.cancelled flag from time
    to time to be able to abort pre-emptively if the job was cancelled instead
    of running forever.
    """

    with synchronized(self):
      cancelled = self.__cancelled
      if not cancelled:
        self.__cancelled = True
        notify_all(self)

    if not cancelled:
      self._trigger_event(Job.CANCELLED)