Run the worker function with some custom exception handling.
179425
def _run(self):
        """"""
        try:
            # Run the worker
            self.worker()
        except SystemExit as ex:
            # sys.exit() was called
            if isinstance(ex.code, int):
                if ex.code is not None and ex.code != 0:
                    # A custom exit code was specified
                    self._shutdown(
                        'Exiting with non-zero exit code {exitcode}'.format(
                            exitcode=ex.code),
                        ex.code)
            else:
                # A message was passed to sys.exit()
                self._shutdown(
                    'Exiting with message: {msg}'.format(msg=ex.code), 1)
        except Exception as ex:
            if self.detach:
                self._shutdown('Dying due to unhandled {cls}: {msg}'.format(
                    cls=ex.__class__.__name__, msg=str(ex)), 127)
            else:
                # We're not detached so just raise the exception
                raise

        self._shutdown('Shutting down normally')
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.')
711420
def run(self):
    """"""
    while True:
      try:
        self._poll_for_update()
      except RuntimeError as error:
        # Note that because logging triggers a call to notify_update(), by
        # logging a message, we automatically retry publishing the update
        # after an error occurs.
        if error.message == 'dictionary changed size during iteration':
          # These errors occur occasionally and it is infeasible to get rid of
          # them entirely unless data.convert_to_base_types() is made
          # thread-safe. Ignore the error and retry quickly.
          _LOG.debug('Ignoring (probably harmless) error in station watcher: '
                     '`dictionary changed size during iteration`.')
          time.sleep(0.1)
        else:
          _LOG.exception('Error in station watcher: %s', error)
          time.sleep(1)
      except Exception as error:  # pylint: disable=broad-except
        _LOG.exception('Error in station watcher: %s', error)
        time.sleep(1)
702228
def run(self, target, callback = None, name = None, complete = None, *args, **kargs):
        
        self.count_lock.acquire()
        if not self.workers:
            self.count_lock.release()
            self.add(name = name)
        else:
            self.count_lock.release()
        self.tasks.put((target, callback, name, complete, args, kargs))
315700
public function run()
    {
        try {
            $this->loop->run();
        } catch (WorkerException $e) {
            $this->logger->error('Worker Error: ' . $e->getMessage());
        }
    }
1097028
def run(self):
        
        log_total = True

        try:
            try:
                # Preparation steps
                self.get_options()

                # Template method with the tool's main loop
                self.mainloop()
            except error.LoggableError, exc:
                if self.options.debug:
                    raise

                # Log errors caused by invalid user input
                try:
                    msg = str(exc)
                except UnicodeError:
                    msg = unicode(exc, "UTF-8")
                self.LOG.error(msg)
                sys.exit(error.EX_SOFTWARE)
            except KeyboardInterrupt, exc:
                if self.options.debug:
                    raise

                sys.stderr.write("\n\nAborted by CTRL-C!\n")
                sys.stderr.flush()
                sys.exit(error.EX_TEMPFAIL)
            except IOError, exc:
                # [Errno 32] Broken pipe?
                if exc.errno == errno.EPIPE:
                    sys.stderr.write("\n%s, exiting!\n" % exc)
                    sys.stderr.flush()

                    # Monkey patch to prevent an exception during logging shutdown
                    try:
                        handlers = logging._handlerList
                    except AttributeError:
                        pass
                    else:
                        for handler in handlers:
                            try:
                                handler.flush = lambda *_: None
                            except AttributeError:
                                pass # skip special handlers

                    log_total = False
                    sys.exit(error.EX_IOERR)
                else:
                    raise
        finally:
            # Shut down
            if log_total and self.options:  ## No time logging on --version and such
                running_time = time.time() - self.startup
                self.LOG.log(self.STD_LOG_LEVEL, "Total time: %.3f seconds." % running_time)
            logging.shutdown()

        # Special exit code?
        if self.return_code:
            sys.exit(self.return_code)
873281
def worker_process(params, channel):
    """"""
    signal(SIGINT, SIG_IGN)

    if params.initializer is not None:
        if not run_initializer(params.initializer, params.initargs):
            os._exit(1)

    try:
        for task in worker_get_next_task(channel, params.max_tasks):
            payload = task.payload
            result = process_execute(
                payload.function, *payload.args, **payload.kwargs)
            send_result(channel, Result(task.id, result))
    except (EnvironmentError, OSError, RuntimeError) as error:
        os._exit(error.errno if error.errno else 1)
    except EOFError:
        os._exit(0)
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()
1310471
public void run() throws Exception {
    if (config == null) {
      return;
    }
    config.channels = 1;
    config.directExecutor = true;
    ManagedChannel ch = config.newChannel();
    SimpleRequest req = config.newRequest();
    LoadGenerationWorker worker =
        new LoadGenerationWorker(ch, req, config.targetQps, config.duration);
    final long start = System.nanoTime();
    Histogram histogram = worker.call();
    final long end = System.nanoTime();
    printStats(histogram, end - start);
    if (config.histogramFile != null) {
      saveHistogram(histogram, config.histogramFile);
    }
    ch.shutdown();
  }
499819
def execute(self, compiled=None, path=None, use_eval=False, allow_show=True):
        """"""
        self.check_runner()
        if compiled is not None:
            if allow_show and self.show:
                print(compiled)
            if path is not None:  # path means header is included, and thus encoding must be removed
                compiled = rem_encoding(compiled)
            self.runner.run(compiled, use_eval=use_eval, path=path, all_errors_exit=(path is not None))
            self.run_mypy(code=self.runner.was_run_code())
625053
def run(config, start, end, accounts, region, debug):
    """"""
    config = validate.callback(config)
    destination = config.get('destination')
    start = start and parse(start) or start
    end = end and parse(end) or datetime.now()
    executor = debug and MainThreadExecutor or ThreadPoolExecutor
    with executor(max_workers=32) as w:
        futures = {}
        for account in config.get('accounts', ()):
            if accounts and account['name'] not in accounts:
                continue
            futures[
                w.submit(process_account, account, start,
                         end, destination, region)] = account
        for f in as_completed(futures):
            account = futures[f]
            if f.exception():
                log.error("Error on account %s err: %s",
                          account['name'], f.exception())
            log.info("Completed %s", account['name'])
15884
def handle(self, *args, **options):
        
        from django.db import connection
        connection.close()
        failed_tries = settings.DJANGO_TH.get('failed_tries', 10)
        trigger = TriggerService.objects.filter(
            Q(provider_failed__lte=failed_tries) |
            Q(consumer_failed__lte=failed_tries),
            status=True,
            user__is_active=True,
            provider__name__status=True,
            consumer__name__status=True,
        ).select_related('consumer__name', 'provider__name')

        with ThreadPoolExecutor(max_workers=settings.DJANGO_TH.get('processes')) as executor:
            r = Read()
            for t in trigger:
                executor.submit(r.reading, t)
1054617
def run():
    """"""
    _parser_options()
    set_verbose(args["verbose"])
    
    if _check_global_settings():
        _load_db()
    else:
        exit(-1)

    #Check the server configuration against the script arguments passed in.
    _setup_server()

    if args["rollback"]:
        _server_rollback()
        okay("The server rollback appears to have been successful.")
        exit(0)

    _server_enable()    
    _list_repos()
    _handle_install()
    
    #This is the workhorse once a successful installation has happened.
    _do_cron()
564438
def _run_callbacks(self):
        """"""
        for i in range(len(self._callbacks)):
            callback, args = self._callbacks.popleft()
            try:
                callback(*args)
            except Exception:
                self._log.exception('Ignoring exception in callback:')
863291
def execute(function, *args, **kwargs):
    """"""
    try:
        return function(*args, **kwargs)
    except Exception as error:
        error.traceback = format_exc()
        return error
379855
def run(delayed, concurrency, version_type=None, queue=None,
        raise_on_error=True):
    """"""
    if delayed:
        celery_kwargs = {
            'kwargs': {
                'version_type': version_type,
                'es_bulk_kwargs': {'raise_on_error': raise_on_error},
            }
        }
        click.secho(
            'Starting {0} tasks for indexing records...'.format(concurrency),
            fg='green')
        if queue is not None:
            celery_kwargs.update({'queue': queue})
        for c in range(0, concurrency):
            process_bulk_queue.apply_async(**celery_kwargs)
    else:
        click.secho('Indexing records...', fg='green')
        RecordIndexer(version_type=version_type).process_bulk_queue(
            es_bulk_kwargs={'raise_on_error': raise_on_error})
921289
def execute():
    """"""

    if len(sys.argv) <= 1:
        raise SystemExit(
            'No Arguments provided. use [--help] for more information.'
        )

    # Capture user arguments
    _args = arguments.ArgumentParserator(
        arguments_dict=turbolift.ARGUMENTS,
        env_name='TURBO',
        epilog=turbolift.VINFO,
        title='Turbolift',
        detail='Multiprocessing Swift CLI tool.',
        description='Manage Swift easily and fast.'
    )
    user_args = _args.arg_parser()
    user_args['run_indicator'] = True
    debug_log = False
    stream_logs = True

    # Load system logging
    if user_args.get('debug'):
        debug_log = True
        user_args['run_indicator'] = False

    # Load system logging
    if user_args.get('quiet'):
        stream_logs = False
        user_args['run_indicator'] = False

    _logging = logger.LogSetup(
        debug_logging=debug_log,
        colorized_messages=user_args.get('colorized', False)
    )
    _logging.default_logger(name='turbolift', enable_stream=stream_logs)
    job = worker.Worker(job_args=user_args)
    job.run_manager()