Do the job.
Throw exceptions on errors (the job will be retried).
506250
public function execute() {
        global $CFG, $DB;

        if ($CFG->enableportfolios) {
            require_once($CFG->libdir . '/portfoliolib.php');
            require_once($CFG->libdir . '/portfolio/exporter.php');
            if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', [time()], '', 'id')) {
                foreach ($expired as $tempdata) {
                    try {
                        $exporter = \portfolio_exporter::rewaken_object($tempdata->id);
                        $exporter->process_stage_cleanup(true);
                    } catch (\Exception $exception) {
                        mtrace('Exception thrown in portfolio cron while cleaning up ' . $tempdata->id . ': ' .
                                $exception->getMessage());
                    }
                }
            }

            $process = $DB->get_records('portfolio_tempdata', ['queued' => 1], 'id ASC', 'id');
            foreach ($process as $tempdata) {
                try {
                    $exporter = \portfolio_exporter::rewaken_object($tempdata->id);
                    $exporter->process_stage_package();
                    $exporter->process_stage_send();
                    $exporter->save();
                    $exporter->process_stage_cleanup();
                } catch (\Exception $exception) {
                    // This will get probably retried in the next cron until it is discarded by the code above.
                    mtrace('Exception thrown in portfolio cron while processing ' . $tempdata->id . ': ' .
                            $exception->getMessage());
                }
            }
        }
    }
107028
def run(self):
        """"""
        while True:
            self.running = True
            workunit = self._workq.get()
            if is_sentinel(workunit):
                # Got sentinel
                break

            # Run the job / sequence
            workunit.process()
        self.running = False
310730
def run(self, *args, **kwargs):
    """"""

    for job in self.jobs:
      job.run(*args, **kwargs)
1022981
def run_job():
    """"""
    async = get_current_async()
    async_options = async.get_options()

    job = async_options.get('job')
    if not job:
        raise Exception('This async contains no job to execute!')

    __, args, kwargs = job

    if args is None:
        args = ()

    if kwargs is None:
        kwargs = {}

    function = async._decorate_job()

    try:
        async.executing = True
        async.result = AsyncResult(payload=function(*args, **kwargs),
                                   status=AsyncResult.SUCCESS)
    except Abort as abort:
        logging.info('Async job was aborted: %r', abort)
        async.result = AsyncResult(status=AsyncResult.ABORT)

        # QUESTION: In this eventuality, we should probably tell the context we
        # are "complete" and let it handle completion checking.
        _handle_context_completion_check(async)
        return
    except AbortAndRestart as restart:
        logging.info('Async job was aborted and restarted: %r', restart)
        raise
    except BaseException as e:
        async.result = AsyncResult(payload=encode_exception(e),
                                   status=AsyncResult.ERROR)

    _handle_results(async_options)
    _handle_context_completion_check(async)
725147
public function handle()
    {
        if ($this->container['queue.failer']->forget($this->argument('id'))) {
            $this->info('Failed job deleted successfully!');
        } else {
            $this->error('No failed job matches the given ID.');
        }
    }
1060440
def execute(self, *args, **kwargs):
        
        self.walk(*args, **kwargs)

        failed_steps = [step for step in self.steps if step.status == FAILED]
        if failed_steps:
            raise PlanFailed(failed_steps)
1343252
public function perform(Job $job)
    {
        try {
            Event::trigger('afterFork', $job);
            $job->perform();
        } catch(Exception $e) {
            $this->log($job . ' failed: ' . $e->getMessage());
            $job->fail($e);
            return;
        }

        $job->updateStatus(Status::STATUS_COMPLETE);
        $this->log('done ' . $job);
    }
186027
public function run() {
        # pull the handler from the db
        $handler = $this->getHandler();
        if (!is_object($handler)) {
            $msg = "[JOB] bad handler for job::{$this->job_id}";
            $this->finishWithError($msg);
            return false;
        }

        # run the handler
        try {

            if ($this->fail_on_output) {
                ob_start();                
            }

            $handler->perform();

            if ($this->fail_on_output) {
                $output = ob_get_contents();
                ob_end_clean();

                if (!empty($output)) {
                    throw new Exception("Job produced unexpected output: $output");
                }
            }

            # cleanup
            $this->finish();
            return true;

        } catch (DJRetryException $e) {
            if ($this->fail_on_output) {
                ob_end_flush();
            }
            
            # attempts hasn't been incremented yet.
            $attempts = $this->getAttempts()+1;

            $msg = "Caught DJRetryException \"{$e->getMessage()}\" on attempt $attempts/{$this->max_attempts}.";

            if($attempts == $this->max_attempts) {
                $msg = "[JOB] job::{$this->job_id} $msg Giving up.";
                $this->finishWithError($msg, $handler);
            } else {
                $this->log("[JOB] job::{$this->job_id} $msg Try again in {$e->getDelay()} seconds.", self::WARN);
                $this->retryLater($e->getDelay());
            }
            return false;

        } catch (Exception $e) {
            if ($this->fail_on_output) {
                ob_end_flush();
            }

            $this->finishWithError($e->getMessage(), $handler);
            return false;

        }
    }
747567
public void runJob()
    {
        try {
            this.currentJob = this.jobQueue.take();

            // Create a clean Execution Context
            ExecutionContext context = new ExecutionContext();

            try {
                this.executionContextManager.initialize(context);
            } catch (ExecutionContextException e) {
                throw new RuntimeException("Failed to initialize Job " + this.currentJob + " execution context", e);
            }

            this.currentJob.run();
        } catch (InterruptedException e) {
            // Thread has been stopped
        } finally {
            this.execution.removeContext();
        }
    }
1207858
def run(self):
        ""
        while 1:
            # Sleep until there is a job to perform.
            job = self.jobs.get()

            # Yawn. Time to get some work done.
            try:
                job.run()
                self.jobs.task_done()
            except TerminationNotice:
                self.jobs.task_done()
                break
588314
def run(self):
        
        try:
            self._loop()
        except Exception:
            # Send the exception through the exc_queue, so the parent
            # process can check it.
            typ, val, tb = sys.exc_info()
            tb_lines = traceback.format_exception(typ, val, tb)
            self.exc_queue.put((val, tb_lines))
745757
def run(self):
        
        try:
            quit_request_detected = False
            while True:
                function, arguments = self.task_queue.get()
                if function is None:
                    # this allows us to watch the threads die and identify
                    # threads that may be hanging or deadlocked
                    self.config.logger.info('quits')
                    break
                if quit_request_detected:
                    continue
                try:
                    try:
                        args, kwargs = arguments
                    except ValueError:
                        args = arguments
                        kwargs = {}
                    function(*args, **kwargs)  # execute the task
                except Exception:
                    self.config.logger.error("Error in processing a job",
                                             exc_info=True)
                except KeyboardInterrupt:  # TODO: can probably go away
                    self.config.logger.info('quit request detected')
                    quit_request_detected = True
                    #thread.interrupt_main()  # only needed if signal handler
                                             # not registered
        except Exception:
            self.config.logger.critical("Failure in task_queue", exc_info=True)
259977
def _do_cb(self, task, cb, error_cb, *args, **kw):
        
        try:
            res = self.work(task, *args, **kw)
        except BackendProcessingError as e:
            if error_cb is None:
                self.log(ERROR, e.__traceback__)
                show_err()
            elif error_cb:
                error_cb(e)
        else:
            # Success, let's call away!
            cb(res)
890979
public function handle()
    {
        if ($this->laravel['queue.failer']->forget($this->argument('id'))) {
            $this->info('Failed job deleted successfully!');
        } else {
            $this->error('No failed job matches the given ID.');
        }
    }
99054
public function perform(ResqueJobBase $job)
    {
        try {
            $this->resqueInstance->events->trigger('afterFork', $job);
            $result = $job->perform();
            if ($result instanceof \Exception) {
                $this->logger->log(LogLevel::CRITICAL, '{job} has failed {message} at the line {line}',
                    [
                        'job' => $job,
                        'message' => $result->getMessage(),
                        'line' => $result->getLine()
                    ]);
                return;
            }
        } catch (\Exception $e) {
            $this->logger->log(LogLevel::CRITICAL, '{job} has failed {message} at the line {line}',
                [
                    'job' => $job,
                    'message' => $e->getMessage(),
                    'line' => $e->getLine()
                ]);
            return;
        }

        $job->status->update(ResqueJobStatus::STATUS_COMPLETE);
        $this->logger->log(LogLevel::NOTICE, '{job} has finished', ['job' => $job]);
    }
859640
def report_failed_job(job,exception)
      log_with_severity :error, "#{job.inspect} failed: #{exception.inspect}"
      begin
        job.fail(exception)
      rescue Object => exception
        log_with_severity :error, "Received exception when reporting failure: #{exception.inspect}"
      end
      begin
        failed!
      rescue Object => exception
        log_with_severity :error, "Received exception when increasing failed jobs counter (redis issue) : #{exception.inspect}"
      end
    end
438446
def handle_an_error():
    """"""
    import os

    from furious.context import get_current_async

    async = get_current_async()
    async_exception = async.result.payload
    exc_info = async_exception.traceback
    logging.info('async job blew up, exception info: %r', exc_info)

    retries = int(os.environ['HTTP_X_APPENGINE_TASKRETRYCOUNT'])
    if retries < 2:
        raise Exception(async_exception.error)
    else:
        logging.info('Caught too many errors, giving up now.')