Do the job.
Throw exceptions on errors (the job will be retried).
507950
public function execute() {
        global $CFG;
        require_once($CFG->dirroot . '/question/engine/lib.php');

        // We delete previews that have not been touched for 24 hours.
        $lastmodifiedcutoff = time() - DAYSECS;

        mtrace("\n  Cleaning up old question previews...", '');
        $oldpreviews = new \qubaid_join('{question_usages} quba', 'quba.id',
            'quba.component = :qubacomponent
                    AND NOT EXISTS (
                        SELECT 1
                          FROM {question_attempts}      subq_qa
                          JOIN {question_attempt_steps} subq_qas ON subq_qas.questionattemptid = subq_qa.id
                          JOIN {question_usages}        subq_qu  ON subq_qu.id = subq_qa.questionusageid
                         WHERE subq_qa.questionusageid = quba.id
                           AND subq_qu.component = :qubacomponent2
                           AND (subq_qa.timemodified > :qamodifiedcutoff
                                    OR subq_qas.timecreated > :stepcreatedcutoff)
                    )
            ',
            ['qubacomponent' => 'core_question_preview', 'qubacomponent2' => 'core_question_preview',
                'qamodifiedcutoff' => $lastmodifiedcutoff, 'stepcreatedcutoff' => $lastmodifiedcutoff]);

        \question_engine::delete_questions_usage_by_activities($oldpreviews);
        mtrace('done.');
    }
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
12139
def perform_job(self, job):
        

        if self.config["trace_memory"]:
            job.trace_memory_start()

        set_current_job(job)

        try:
            job.perform()

        except MaxConcurrencyInterrupt:
            self.log.error("Max concurrency reached")
            job._save_status("maxconcurrency", exception=True)

        except RetryInterrupt:
            self.log.error("Caught retry")
            job.save_retry(sys.exc_info()[1])

        except MaxRetriesInterrupt:
            self.log.error("Max retries reached")
            job._save_status("maxretries", exception=True)

        except AbortInterrupt:
            self.log.error("Caught abort")
            job.save_abort()

        except TimeoutInterrupt:
            self.log.error("Job timeouted after %s seconds" % job.timeout)
            job._save_status("timeout", exception=True)

        except JobInterrupt:
            self.log.error("Job interrupted")
            job._save_status("interrupt", exception=True)

        except Exception:
            self.log.error("Job failed")
            job._save_status("failed", exception=True)

        finally:

            set_current_job(None)

            self.done_jobs += 1

            if self.config["trace_memory"]:
                job.trace_memory_stop()
180699
def perform(job)
      begin
        if fork_per_job?
          reconnect
          run_hook :after_fork, job
        end
        job.perform
      rescue Object => e
        report_failed_job(job,e)
      else
        log_with_severity :info, "done: #{job.inspect}"
      ensure
        yield job if block_given?
      end
    end
1229597
private void tryRunNext() {
        while (runningSemaphore.tryAcquire()) {
            ExecutionTask execution = queue.poll();
            if (execution != null) {
                // Note: we've removed the execution from the queue so we're committed to running it
                // if we fail to do so for any reason, we need to call the exception handler to fail the execution
                try {
                    execution.submit();
                } catch (Throwable e) {
                    // Any exception here is unexpected
                    runningSemaphore.release();
                    execution.exceptionHandler.handle(e);
                }
            } else {
                runningSemaphore.release();
                break;
            }
        }
    }
258562
public function run()
    {
        try {
            $this->header('Content-Type: text/plain');
        } catch (\Exception $e) {
        }
        var_dump($this->job->getResult('query'));
        var_dump($this->job->getResult('resolve'));
    }
218210
def handle(self):
        ''''''
        try:
            yield self
        except:
            # Requeue the message and raise the original exception
            typ, value, trace = sys.exc_info()
            if not self.processed:
                try:
                    self.req(self.delay())
                except socket.error:
                    self.connection.close()
            raise typ, value, trace
        else:
            if not self.processed:
                try:
                    self.fin()
                except socket.error:
                    self.connection.close()
555565
void executeInABox(final Job job) {
        try {
            job.execute();
        } catch (Exception e) {
            System.err.println("The execution of the job threw an exception");
            e.printStackTrace(System.err);
        }
    }
152170
def submit_comp_job(self, path, callback, method, *args, **kwargs):
        """"""
        if self.executor is None:
            with self.handling_exceptions():
                callback(getattr(self.comp, method)(*args, **kwargs))
        else:
            path = showpath(path)
            with logger.in_path(path):  # pickle the compiler in the path context
                future = self.executor.submit(multiprocess_wrapper(self.comp, method), *args, **kwargs)

            def callback_wrapper(completed_future):
                """Ensures that all errors are always caught, since errors raised in a callback won't be propagated."""
                with logger.in_path(path):  # handle errors in the path context
                    with self.handling_exceptions():
                        result = completed_future.result()
                        callback(result)
            future.add_done_callback(callback_wrapper)
1320444
public void execute(Runnable job)
   {
      try
      {       
         executor.execute(job);
      }
      catch (RejectedExecutionException e)
      {
         log.warnf(e, "Job rejected: %s", job);
      }
   }
352651
def retry(self):
        

        logger.info('Job {0} retrying all failed tasks'.format(self.name))
        self.initialize_snapshot()

        failed_task_names = []
        for task_name, log in self.run_log['tasks'].items():
            if log.get('success', True) == False:
                failed_task_names.append(task_name)

        if len(failed_task_names) == 0:
            raise DagobahError('no failed tasks to retry')

        self._set_status('running')
        self.run_log['last_retry_time'] = datetime.utcnow()

        logger.debug('Job {0} seeding run logs'.format(self.name))
        for task_name in failed_task_names:
            self._put_task_in_run_log(task_name)
            self.tasks[task_name].start()

        self._commit_run_log()
833115
@Override
    public void run() {
        try {
            handle();
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }
582623
def _execute_handling(self, *eopatches, **kwargs):
        
        self.private_task_config.start_time = datetime.datetime.now()

        caught_exception = None
        try:
            return_value = self.execute(*eopatches, **kwargs)
        except BaseException as exception:
            caught_exception = exception, sys.exc_info()[2]

        if caught_exception is not None:  # Exception is not raised in except statement to prevent duplicated traceback
            exception, traceback = caught_exception
            raise type(exception)('During execution of task {}: {}'.format(self.__class__.__name__,
                                                                           exception)).with_traceback(traceback)

        self.private_task_config.end_time = datetime.datetime.now()
        return return_value
1230118
public function perform(): void
    {
        $reason = null;
        try { // try executing task
            $this->project->fireTaskStarted($this);
            $this->maybeConfigure();
            DispatchUtils::main($this);
        } catch (\BuildException $ex) {
            $loc = $ex->getLocation();
            if ($loc === null || (string) $loc === '') {
                $ex->setLocation($this->getLocation());
            }
            $reason = $ex;
            throw $ex;
        } catch (\Exception $ex) {
            $reason = $ex;
            $be = new \BuildException($ex);
            $be->setLocation($this->getLocation());
            throw $be;
        } catch (\Error $ex) {
            $reason = $ex;
            throw $ex;
        } finally {
            $this->project->fireTaskFinished($this, $reason);
        }
    }
729200
@Override
    public void execute() throws BuildException {
        initialize();

        final Job job = getJob(tempDir, getProject());
        try {
            for (final ModuleElem m : modules) {
                m.setProject(getProject());
                m.setLocation(getLocation());
                final PipelineHashIO pipelineInput = new PipelineHashIO();
                for (final Map.Entry<String, String> e : attrs.entrySet()) {
                    pipelineInput.setAttribute(e.getKey(), e.getValue());
                }
                AbstractPipelineModule mod = getPipelineModule(m, pipelineInput);
                long start = System.currentTimeMillis();
                mod.setLogger(logger);
                mod.setJob(job);
                mod.execute(pipelineInput);
                long end = System.currentTimeMillis();
                logger.debug("{0} processing took {1} ms", mod.getClass().getSimpleName(), end - start);
            }
        } catch (final DITAOTException e) {
            throw new BuildException("Failed to run pipeline: " + e.getMessage(), e);
        }
    }
849543
def exception(self):
    

    if self.__state in (Job.PENDING, Job.RUNNING):
      raise self.InvalidState('job is {0}'.format(self.__state))
    elif self.__state == Job.ERROR:
      assert self.__exception is not None
      return self.__exception
    elif self.__state in (Job.RUNNING, Job.SUCCESS, Job.CANCELLED):
      assert self.__exception is None
      return None
    else:
      raise RuntimeError('invalid job state {0!r}'.format(self.__state))
1237357
public function performTasks()
    {
        try { // try to execute this target
            $this->project->fireTargetStarted($this);
            $this->main();
            $this->project->fireTargetFinished($this, $null = null);
        } catch (BuildException $exc) {
            // log here and rethrow
            $this->project->fireTargetFinished($this, $exc);
            throw $exc;
        }
    }