Runs each timer handler in a separate greenlet thread.
968132
def handle_timer_event(self, handler):
        
        while True:
            handler(self)
            sleep(handler.event.args["seconds"])
1119424
def execute_greenlet_async(func, *args, **kwargs):
  
  global _GREENLET_EXECUTOR
  if _GREENLET_EXECUTOR is None:
    _GREENLET_EXECUTOR = GreenletExecutor(
      num_greenlets=settings.node.greenlet_pool_size)
  return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
400016
async def run_with_reloader(loop, coroutine, cleanup=None, *args, **kwargs):
    

    clear_screen()
    print("🤖  Running in debug mode with live reloading")
    print("    (don't forget to disable it for production)")

    # Create watcher
    handler = Handler(loop)
    watcher = Observer()

    # Setup
    path = realpath(os.getcwd())
    watcher.schedule(handler, path=path, recursive=True)
    watcher.start()

    print("    (watching {})".format(path))

    # Run watcher and coroutine together
    done, pending = await asyncio.wait(
        [coroutine, handler.changed], return_when=asyncio.FIRST_COMPLETED
    )

    # Cleanup
    cleanup and cleanup()
    watcher.stop()

    for fut in done:
        # If change event, then reload
        if isinstance(fut.result(), Event):
            print("Reloading...")
            reload()
41432
def watch(*timer_args, **timer_kwargs):
        """"""

        def wrapper(function):
            @wraps(function)
            def inner(*args, **kwargs):
                args1 = ", ".join(map(repr, args)) if args else ""
                kwargs1 = ", ".join(
                    ["%s=%s" % (i, repr(kwargs[i])) for i in sorted(kwargs.keys())]
                )
                arg = ", ".join(filter(None, [args1, kwargs1]))
                name = "%s(%s)" % (function.__name__, arg)
                _ = Timer(name=name, *timer_args, **timer_kwargs)
                result = function(*args, **kwargs)
                return result

            return inner

        return wrapper
1037458
def run(self):
        """"""

        idle_watchers = []

        while True:
            try:
                if self._work_queue.empty() and len(idle_watchers) > 0:
                    for watcher in idle_watchers:
                        try:
                            watcher()
                        except: # pylint:disable=bare-except;We can't let one idle watcher failure impact any other watcher
                            self._logger.exception("Error inside queue idle watcher")

                    idle_watchers = []

                item = self._work_queue.get()

                # Handle special actions that are not RPCs
                if item is STOP_WORKER_ITEM:
                    return
                elif isinstance(item, MarkLocationItem):
                    item.callback()
                    continue
                elif isinstance(item, WaitIdleItem):
                    idle_watchers.append(item.callback)
                    continue
                elif not isinstance(item, WorkItem):
                    self._logger.error("Invalid item passed to WorkQueueThread: %s, ignoring", item)
                    continue

                self.direct_dispatch(item.arg, item.callback)

            except:  # pylint:disable=bare-except;We cannot let this background thread die until we are told to stop()
                self._logger.exception("Error inside background workqueue thread")
773410
def mainLoop(self):
        """"""
        self.greenlet = gevent.getcurrent()
        callqueue = self._callqueue
        seconds = self.seconds
        try:
            while 1:
                self._wait = 0
                now = seconds()
                if len(callqueue) > 0:
                    self._wake = delay = callqueue[0].time
                    delay -= now
                else:
                    self._wake = now + 300
                    delay = 300
                try:
                    self._wait = 1
                    try:
                        self._threadCallNotification.get(timeout=delay if delay > 0 else 0)
                    except Empty:
                        pass
                    else:
                        raise Reschedule
                    self._wait = 0
                except Reschedule:
                    if self.threadCallQueue:
                        total = len(self.threadCallQueue)
                        count = 0
                        for fn, args, kwargs in self.threadCallQueue:
                            try:
                                fn(*args, **kwargs)
                            except:
                                log.err()
                            count += 1
                            if count == total:
                                break
                        del self.threadCallQueue[:count]
                        if self.threadCallQueue:
                            self.wakeUp()
                    continue
                now = seconds()
                while 1:
                    try:
                        c = callqueue[0]
                    except IndexError:
                        break
                    if c.time <= now:
                        del callqueue[0]
                        try:
                            c()
                        except GreenletExit:
                            raise
                        except:
                            log.msg('Unexpected error in main loop.')
                            log.err()
                    else:
                        break
        except (GreenletExit, KeyboardInterrupt):
            pass
        log.msg('Main loop terminated.')
        self.fireSystemEvent('shutdown')
1007631
def run(self):
        """"""
        event_handler = Handler()
        threads = []
        paths = [os.path.join(cwd, "content"), os.path.join(cwd, "templates")]

        for i in paths:
            targetPath = str(i)
            self.observer.schedule(event_handler, targetPath, recursive=True)
            threads.append(self.observer)

        self.observer.start()

        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("\nObserver stopped.")

        self.observer.join()
624819
@Override
  public void run() {

    LOG.entering(CLASS_NAME, "run");

    try {

      LOG.log(Level.FINE, "Subscribe event handlers");

      subscribe(StartTime.class, this.startHandler.get());
      subscribe(StopTime.class, this.stopHandler.get());
      subscribe(RuntimeStart.class, this.runtimeStartHandler.get());
      subscribe(RuntimeStop.class, this.runtimeStopHandler.get());
      subscribe(IdleClock.class, this.idleHandler.get());

      LOG.log(Level.FINE, "Initiate runtime start");
      this.handlers.onNext(new RuntimeStart(this.timer.getCurrent()));

      LOG.log(Level.FINE, "Initiate start time");
      this.handlers.onNext(new StartTime(this.timer.getCurrent()));

      while (true) {

        LOG.log(Level.FINEST, "Enter clock main loop.");

        try {

          if (this.isIdle()) {
            // Handle an idle clock event, without locking this.schedule
            this.handlers.onNext(new IdleClock(this.timer.getCurrent()));
          }

          final Time event;
          final int eventQueueLen;
          synchronized (this.schedule) {

            while (this.schedule.isEmpty()) {
              this.schedule.wait();
            }

            assert this.schedule.first() != null;

            // Wait until the first scheduled time is ready.
            // NOTE: while waiting, another alarm could be scheduled with a shorter duration
            // so the next time I go around the loop I need to revise my duration.
            while (true) {
              final long waitDuration = this.timer.getDuration(this.schedule.first());
              if (waitDuration <= 0) {
                break;
              }
              this.schedule.wait(waitDuration);
            }

            // Remove the event from the schedule and process it:
            event = this.schedule.pollFirst();

            if (event instanceof ClientAlarm) {
              --this.numClientAlarms;
              assert this.numClientAlarms >= 0;
            }

            eventQueueLen = this.numClientAlarms;
          }

          assert event != null;

          LOG.log(Level.FINER,
              "Process event: {0} Outstanding client alarms: {1}", new Object[] {event, eventQueueLen});

          if (event instanceof Alarm) {
            ((Alarm) event).run();
          } else {
            this.handlers.onNext(event);
            if (event instanceof StopTime) {
              break; // we're done.
            }
          }

        } catch (final InterruptedException expected) {
          LOG.log(Level.FINEST, "Wait interrupted; continue event loop.");
        }
      }

      this.handlers.onNext(new RuntimeStop(this.timer.getCurrent(), this.exceptionCausedStop));

    } catch (final Exception e) {

      LOG.log(Level.SEVERE, "Error in runtime clock", e);
      this.handlers.onNext(new RuntimeStop(this.timer.getCurrent(), e));

    } finally {
      LOG.log(Level.FINE, "Runtime clock exit");
    }

    LOG.exiting(CLASS_NAME, "run");
  }
1070616
def fire(self, *args, **kwargs):
        """"""
        if self.eventmanager:
            # Fire global event. Assuming we have an eventmanager.
            self.eventmanager.got_event(self.name, *args, **kwargs)

        for handler in self:  # Iterate over handlers
            try:
                handler(*args, **kwargs)  # Execute handler with given args.
            except StopIteration:  # Stop iterating if handler raised StopIter
                break
1282632
public void doEvents() {
		while (!isInterrupted()) {
			Iterator<Map.Entry<Timer, Runnable>> it = timerMap.entrySet().iterator();
			if (it.hasNext()) {
				long timeout = it.next().getKey().uptime - System.currentTimeMillis();
				doEvents(timeout > 0 ? timeout : 0);
			} else {
				doEvents(-1);
			}
		}
	}
186669
public synchronized void start() {
        if (!running) {
            checkState(timer == null);

            timer = new java.util.Timer(true); // use daemon thread internally
            schedulePurging(); // schedule timeout to purge cancelled tasks from the timer task queue

            running = true;
        }
    }
254523
def run_in_greenlet(callable):
    
    @wraps(callable)
    async def _(*args, **kwargs):
        green = greenlet(callable)
        # switch to the new greenlet
        result = green.switch(*args, **kwargs)
        # back to the parent
        while isawaitable(result):
            # keep on switching back to the greenlet if we get an awaitable
            try:
                result = green.switch((await result))
            except Exception:
                exc_info = sys.exc_info()
                result = green.throw(*exc_info)

        return green.switch(result)

    return _
498054
def run(self):  # Thread for receiving data from pilight
        """"""
        logging.debug('Pilight receiver thread started')
        if not self.callback:
            raise RuntimeError('No callback function set, cancel readout thread')

        def handle_messages(messages):
            """Call callback on each receive message."""
            for message in messages:  # Loop over received  messages
                if message:  # Can be empty due to splitlines
                    message_dict = json.loads(message.decode())
                    if self.recv_codes_only:
                        # Filter: Only use receiver messages
                        if 'receiver' in message_dict['origin']:
                            if self.veto_repeats:
                                if message_dict.get('repeats', 1) == 1:
                                    self.callback(message_dict)
                            else:
                                self.callback(message_dict)
                    else:
                        self.callback(message_dict)

        while not self._stop_thread.isSet():
            try:  # Read socket in a non blocking call and interpret data
                # Sometimes more than one JSON object is in the stream thus
                # split at \n
                with self._lock:
                    messages = self.receive_socket.recv(1024).splitlines()
                handle_messages(messages)
            except (socket.timeout, ValueError):  # No data
                pass
        logging.debug('Pilight receiver thread stopped')
602737
function TimerWorker(ww) {
  var self = this;

  this.__ww__ = ww;
  this.__timer_handlers__ = {};

  this.__ww__.onmessage = function (event) {
    if (event.data.type === 'tick') {
      self.__timer_handlers__[event.data.id]();
    }
  };
}
312075
public void run() {
		
		final TimerTaskData taskData = task.getData();
		final Serializable taskID = taskData.getTaskID();
		
		if (logger.isDebugEnabled()) {
			logger.debug("Cancelling timer task for timer ID "+taskID);
		}
		
		scheduler.getLocalRunningTasksMap().remove(taskID);
		
		try {
			task.cancel();					
		}
		catch (Throwable e) {
			logger.error(e.getMessage(),e);
		}
	}
645004
def run(self):
        """"""
        self.api = self.context.get("cls")(self.context)
        self.context["inst"].append(self)  # Adapters used by strategies

        for call, calldata in self.context.get("calls", {}).items():
            def loop():
                """Loop on event scheduler, calling calls"""
                while not self.stopped.wait(calldata.get("delay", None)):
                    self.call(call, calldata.get("arguments", None))

            self.thread[call] = Process(target=loop)
            self.thread[call].start()
69190
def fire(self, *args, **kw):
        
        result = []

        with self._hlock:
            handlers = self.handlers

        if self.threads == 0:  # same-thread execution - synchronized
            for k in handlers:
                # handler, memoize, timeout
                h, m, t = handlers[k]
                try:
                    r = self._memoize(h, m, t, *args, **kw)
                    result.append(tuple(r))
                except:
                    result.append((False, self._error(sys.exc_info()), h))

        elif self.threads > 0:  # multi-thread execution - desynchronized if self.threads > 1
            queue = Queue()

            # result lock just in case [].append() is not  
            # thread-safe in other Python implementations
            rlock = RLock()

            def _execute(*args, **kw):
                """ Executes all handlers stored in the queue """
                while True:
                    try:
                        item = queue.get()
                        if item is None:
                            queue.task_done()
                            break

                        # handler, memoize, timeout
                        h, m, t = handlers[item]  # call under active lock

                        try:
                            r = self._memoize(h, m, t, *args, **kw)
                            if not self.asynch:
                                with rlock:
                                    result.append(tuple(r))
                        except:
                            if not self.asynch:
                                with rlock:
                                    result.append((False, self._error(sys.exc_info()), h))

                        queue.task_done()

                    except Empty:  # never triggered, just to be safe
                        break

            if handlers:
                threads = self._threads(handlers=handlers)

                for _ in range(threads):
                    t = Thread(target=_execute, args=args, kwargs=kw)
                    t.daemon = True
                    t.start()

                for k in handlers:
                    queue.put(k)

                    if self.asynch:  # main thread, no locking required
                        h, _, _ = handlers[k]
                        result.append((None, None, h))

                for _ in range(threads):
                    queue.put(None)  # stop each worker

                if not self.asynch:
                    queue.join()

        return tuple(result) or None