Executes the passed block and raises +exception+ if execution takes more
 than +seconds+.

 If +seconds+ is zero or nil, simply executes the block
323083
def timeout(seconds, exception=Timeout::Error)
      return yield if seconds.nil? or seconds.zero?
      # raise ThreadError, "timeout within critical session" if Thread.critical
      id = TimeoutHandler.register(seconds, exception)
      begin
        yield(seconds)
      ensure
        TimeoutHandler.cancel(id)
      end
    end
242535
def run(self):
        
        try:
            while True:
                input_chunks = [input.get() for input in self.input_queues]
                for input in self.input_queues:
                    input.task_done()
                if any(chunk is QUEUE_ABORT for chunk in input_chunks):
                    self.abort()
                    return
                if any(chunk is QUEUE_FINISHED for chunk in input_chunks):
                    break
                self.output(self.process_chunks(input_chunks))
            # Finalise the final chunk (process_chunks does this for all
            # but the last chunk).
            self.output(self.finalise())
        except:
            self.abort()
            raise
        else:
            for queue in self.output_queues:
                queue.put(QUEUE_FINISHED)
526875
def execute(command, silent = false, &block)
      result = run_with_timeout(command)
      if result.success? or silent
        warn command if @verbose
        return result unless block
        return block.call(result)
      end
      raise Error, cmd_error_message(command, result.data)
    rescue Errno::ENOENT
      raise Error, cmd_error_message(command, $!.message)
    end
170940
public void run() {
		try {
			Object result = execute();
			if (!aborted) {
				this.retval = result;
				finished = true;
			}
		}
		catch (InterruptedException ie) {
			//
		}
		catch (Throwable t) {
			execException = t;
			finished = true;
		}
	}
214622
public void executeWithDelay() {
        long now = Clock.currentTimeMillis();
        if (delay + now > hardLimit) {
            scheduleNewExecution(now);
        } else if (!tryPostponeExecution()) {
            scheduleNewExecution(now);
        }
    }
244685
def run(self):
        
        if self._py3_wrapper.running:
            cache_time = None
            # execute each method of this module
            for meth, obj in self.methods.items():
                my_method = self.methods[meth]

                # always check py3status is running
                if not self._py3_wrapper.running:
                    break

                # respect the cache set for this method
                if time() < obj["cached_until"]:
                    if not cache_time or obj["cached_until"] < cache_time:
                        cache_time = obj["cached_until"]
                    continue

                try:
                    # execute method and get its output
                    method = getattr(self.module_class, meth)
                    if my_method["call_type"] == self.PARAMS_NEW:
                        # new style modules
                        response = method()
                    else:
                        # legacy modules had parameters passed
                        response = method(
                            self.i3status_thread.json_list,
                            self.config["py3_config"]["general"],
                        )

                    if isinstance(response, dict):
                        # this is a shiny new module giving a dict response
                        result = response
                    elif isinstance(response, tuple):
                        # this is an old school module reporting its position
                        position, result = response
                        if not isinstance(result, dict):
                            raise TypeError("response should be a dict")
                    else:
                        raise TypeError("response should be a dict")

                    if isinstance(response.get("full_text"), (list, Composite)):
                        response["composite"] = response["full_text"]
                        del response["full_text"]
                    if "composite" in response:
                        self.process_composite(response)
                    else:
                        # validate the response
                        if "full_text" not in result:
                            err = 'missing "full_text" key in response'
                            raise KeyError(err)
                        # Remove any none color from our output
                        if hasattr(result.get("color"), "none_setting"):
                            del result["color"]
                        # remove urgent if not allowed
                        if not self.allow_urgent and "urgent" in result:
                            del result["urgent"]
                        # set universal module options in result
                        result.update(self.i3bar_module_options)

                    result["instance"] = self.module_inst
                    result["name"] = self.module_name

                    # initialize method object
                    if my_method["name"] is None:
                        my_method["name"] = result["name"]
                        if "instance" in result:
                            my_method["instance"] = result["instance"]
                        else:
                            my_method["instance"] = result["name"]

                    # update method object cache
                    if "cached_until" in result:
                        cached_until = result["cached_until"]
                        # remove this so we can check later for output changes
                        del result["cached_until"]
                    else:
                        # get module default cached_until
                        cached_until = self.module_class.py3.time_in()
                    my_method["cached_until"] = cached_until
                    if not cache_time or cached_until < cache_time:
                        cache_time = cached_until

                    # update method object output
                    if "composite" in response:
                        my_method["last_output"] = result["composite"]
                    else:
                        my_method["last_output"] = result

                    # debug info
                    if self.config["debug"]:
                        self._py3_wrapper.log(
                            "method {} returned {} ".format(meth, result)
                        )
                    # module working correctly so ensure module works as
                    # expected
                    self.allow_config_clicks = True
                    self.error_messages = None
                    self.error_hide = False

                    # mark module as updated
                    self.set_updated()

                except ModuleErrorException as e:
                    # module has indicated that it has an error
                    self.runtime_error(e.msg, meth)
                    if e.timeout:
                        if e.timeout is PY3_CACHE_FOREVER:
                            cache_time = PY3_CACHE_FOREVER
                        else:
                            cache_time = time() + e.timeout
                    else:
                        cache_time = time() + getattr(
                            self.module_class,
                            "cache_timeout",
                            self.config["cache_timeout"],
                        )

                except Exception as e:
                    msg = "Instance `{}`, user method `{}` failed"
                    msg = msg.format(self.module_full_name, meth)
                    if not self.testing:
                        self._py3_wrapper.report_exception(msg, notify_user=False)
                    # added error
                    self.runtime_error(str(e) or e.__class__.__name__, meth)
                    cache_time = time() + getattr(
                        self.module_class, "cache_timeout", self.config["cache_timeout"]
                    )

            if cache_time is None:
                cache_time = time() + self.config["cache_timeout"]
            self.cache_time = cache_time
            # new style modules can signal they want to cache forever
            if cache_time == PY3_CACHE_FOREVER:
                return
            # don't be hasty mate
            # set timeout to do update next time one is needed
            if not cache_time:
                cache_time = time() + self.config["minimum_interval"]

            self._py3_wrapper.timeout_queue_add(self, cache_time)
945254
def perform(*args)
      raise Errors::TimeoutNotDefined unless self.class.timeout

      ::Timeout.timeout(self.class.timeout, Errors::TimeoutError) { super }
    end
999335
def do_execute(self):
        
        if isinstance(self.input.payload, Instances):
            inst = None
            data = self.input.payload
        elif isinstance(self.input.payload, Instance):
            inst = self.input.payload
            data = inst.dataset

        index = str(self.resolve_option("index"))
        unset = bool(self.resolve_option("unset"))
        if unset:
            data.no_class()
        else:
            if index == "first":
                data.class_is_first()
            elif index == "last":
                data.class_is_last()
            else:
                data.class_index = int(index) - 1

        if inst is None:
            self._output.append(Token(data))
        else:
            self._output.append(Token(inst))

        return None
63840
public void run()
    {
        if(evalOnly)
            throw new RuntimeException("bsh Interpreter: No stream");

        /*
          We'll print our banner using eval(String) in order to
          exercise the parser and get the basic expression classes loaded...
          This ameliorates the delay after typing the first statement.
        */
        if ( interactive && null == getParent() ) try {
            eval("printBanner();");
        } catch ( EvalError e ) {
            println( "BeanShell " + VERSION );
        }

        // init the callstack.
        CallStack callstack = new CallStack( globalNameSpace );

        SimpleNode node = null;
        EOF = false;
        int idx = -1;
        while( !Thread.interrupted() && !EOF )
        {
            try
            {
                if ( interactive )
                    console.prompt(getBshPrompt());

                EOF = readLine();

                if( get_jjtree().nodeArity() > 0 )  // number of child nodes
                {

                    node = (SimpleNode) (get_jjtree().rootNode());
                    // nodes remember from where they were sourced
                    node.setSourceFile( sourceFileInfo );

                    if( DEBUG.get() )
                        node.dump(">");
                    if ( TRACE )
                        println( "// " +node.getText() );


                    Object ret = node.eval( callstack, this );

                    // sanity check during development
                    if ( callstack.depth() > 1 )
                        throw new InterpreterError(
                            "Callstack growing: "+callstack);

                    if(ret instanceof ReturnControl)
                        ret = ((ReturnControl)ret).value;

                    if (interactive) {
                        if( ret != Primitive.VOID )
                        {
                            setu("$_", ret);
                            setu("$"+(++idx%10), ret);
                            if ( showResults )
                                println("--> $" + (idx%10) + " = " + StringUtil.typeValueString(ret));
                        } else if ( showResults )
                            println("--> void");
                    }
                }
            }
            catch(ParseException e)
            {
                error("Parser Error: " + e.getMessage(DEBUG.get()));
                if ( DEBUG.get() )
                    e.printStackTrace();
                if( !interactive )
                    EOF = true;
                parser.reInitInput(getIn());
            }
            catch(InterpreterError e)
            {
                error("Internal Error: " + e.getMessage());
                if(!interactive)
                    EOF = true;
            }
            catch(TargetError e)
            {
                error("Target Exception: " + e.getMessage() );
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), getErr() );
                if(!interactive)
                    EOF = true;
                setu("$_e", e.getTarget());
            }
            catch (EvalError e)
            {
                if ( interactive )
                    error( "Evaluation Error: "+e.getMessage() );
                else
                    error( "Evaluation Error: "+e.getRawMessage() );
                if(DEBUG.get())
                    e.printStackTrace();
                if(!interactive)
                    EOF = true;
            }
            catch(Exception e)
            {
                error("Unknown error: " + e);
                if ( DEBUG.get() )
                    e.printStackTrace();
                if(!interactive)
                    EOF = true;
            }
            finally
            {
                get_jjtree().reset();
                // reinit the callstack
                if ( callstack.depth() > 1 ) {
                    callstack.clear();
                    callstack.push( globalNameSpace );
                }
            }
        }

        if ( interactive && exitOnEOF )
            System.exit(0);
    }
552381
def execute(args=nil)
      args ||= EMPTY_TASK_ARGS
      if application.options.dryrun
        puts "** Execute (dry run) #{name}"
        return
      end
      if application.options.trace
        puts "** Execute #{name}"
      end
      application.enhance_with_matching_rule(name) if @actions.empty?
      @actions.each do |act|
        case act.arity
        when 1
          act.call(self)
        else
          act.call(self, args)
        end
      end
    end
537849
def execute_sample(to_execute, source: nil)
      # Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected.
      Tools.silence_warnings do
        if to_execute.is_a?(CoveredCode)
          to_execute.execute_code
        else
          to_execute.call
        end
      end
      true
    rescue StandardError => e
      # In our samples, a simple `raise` is expected and doesn't need to be rescued
      return false if e.is_a?(RuntimeError) && e.message.empty?

      source = to_execute.covered_source if to_execute.is_a?(CoveredCode)
      raise unless source

      inner_msg = Tools.indent_string("#{e.class.name}: #{e.message}", 4)
      source = Tools.indent_string(source, 4)
      msg = "Exception when executing the sample:\n#{inner_msg}\n*Code follows*\n#{source}"
      new_exc = ExceptionInSample.new(msg)
      new_exc.set_backtrace(e.backtrace)
      raise new_exc
    end
226169
public void execute() {

        ExecutorService executorService = MoreExecutors.sameThreadExecutor();

        for (Transaction<V, R> transaction : transactions) {
            if (!transaction.isComplete()) {
                executorService.execute(transaction);
            }
        }

        try {
            executorService.shutdown();
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new TransfuseTransactionException("Pool executor interrupted", e);
        }
    }
346874
def run_loop(&block)
      acquired = false
      begin
        until shutdown_pending?
          # The usual situation
          if relock_every != 0
            i ||= 0
            # 0 % anything is 0, so we always try to get the lock on the first loop.
            if (i %= relock_every) == 0
              acquired = lock_function.call(@name)
            end
          else
            # With relock_every set to 0, only acquire the lock once.
            # Hope you're sure that lock beongs to you.
            acquired ||= lock_function.call(@name)
            i = 0 # no point in incrementing something we don't check.
          end

          yield if acquired

          # Sleep one second at a time so we can quickly respond to
          # shutdown requests.
          sleep_for.times do
            sleep(1) unless shutdown_pending?
          end
          i += 1
        end # loop
      rescue ::Interrupt => ex
        log "shutting down after interrupt: #{ex.class} - #{ex.message}"
        shutdown_soon # Always shut down from an Interrupt, even mid-restart.
        return
      rescue ::Exception => ex
        error "restarting after error: #{ex.class} - #{ex.message}"
        error "backtrace: #{ex.backtrace.join("\n")}"
        restart_soon # Restart if we run into an exception.
      end # begin block
    end
630264
def handle_expired_task(exception)
      exception.run_time = Time.now.in_time_zone(@task.time_zone)
      exception.scheduled_time = @scheduled_time
      exception.task = @task

      SimpleScheduler.expired_task_blocks.each do |block|
        block.call(exception)
      end
    end
1040719
def with_timeout(time=@options[:timeout])
      raise ArgumentError, "Block required" if !block_given?
      if Munin::TIMEOUT_CLASS.respond_to?(:timeout_after)
        Munin::TIMEOUT_CLASS.timeout_after(time) { yield }
      else
        Munin::TIMEOUT_CLASS.timeout(time) { yield }
      end
    end
869029
def check(timeout = nil, &block)
      message = nil

      @mutex.lock
      begin
        raise MailboxDead, "attempted to receive from a dead mailbox" if @dead

        message = nil
        Timers::Wait.for(timeout) do |remaining|
          message = next_message(&block)

          break if message

          @condition.wait(@mutex, remaining)
        end
      ensure
        begin
          @mutex.unlock
        rescue
          nil
        end
      end

      message
    end
595390
def instance_methods_eval(&block)
      raise ArgumentError, "block required" unless block_given?

      context = eval('self', block.binding)

      context.send :push_redirection_target, self

      begin
        yield context
      ensure
        context.send :pop_redirection_target
      end

      self
    end