Start a background worker which scans input file
 and triggers any events bound to each one.
482962
def start_watching
      return if @worker
      @worker = Thread.new do
        loop do
          event = read
          next unless ALLOWED_EVENT_TYPES.include?(event.type)
          case event.type
            when BUTTON_TYPE
              RubyHid::Button.trigger_event(event.code, event.value)
            when AXIS_TYPE
              RubyHid::Axis.trigger_event(event.code, event.value)
          end
        end
      end
    end
1159754
def setup_file_watcher(path, use_polling=False):
    
    if use_polling:
        observer_class = watchdog.observers.polling.PollingObserver
    else:
        observer_class = EVENTED_OBSERVER

    file_event_handler = _SourceChangesHandler(patterns=["*.py"])
    file_watcher = observer_class()
    file_watcher.schedule(file_event_handler, path, recursive=True)
    file_watcher.start()
    return file_watcher
1152322
def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
        
        submit_thread = Thread(target=self.submit_reading,
                               args=(input_fname, 0, None, ids_per_job),
                               kwargs={'stagger': stagger},
                               daemon=True)
        submit_thread.start()
        self.watch_and_wait(**wait_params)
        submit_thread.join(0)
        if submit_thread.is_alive():
            logger.warning("Submit thread is still running even after job"
                           "completion.")
        return
171500
function startWatcherForLinting (src)
{
    watch(src,
        function (file)
        {
            if (file.path)
            {
                lintFiles(file.path);
            }
        }
    );
}
648515
def _handle_event(self, sid, namespace, id, data):
        """"""
        namespace = namespace or '/'
        self.logger.info('received event "%s" from %s [%s]', data[0], sid,
                         namespace)
        if self.async_handlers:
            self.start_background_task(self._handle_event_internal, self, sid,
                                       data, namespace, id)
        else:
            self._handle_event_internal(self, sid, data, namespace, id)
1108184
def handle_input(self, event):
        """"""
        self.update_timeval()
        self.events = []
        code = self._get_event_key_code(event)

        if code in self.codes:
            new_code = self.codes[code]
        else:
            new_code = 0
        event_type = self._get_event_type(event)
        value = self._get_key_value(event, event_type)
        scan_event, key_event = self.emulate_press(
            new_code, code, value, self.timeval)

        self.events.append(scan_event)
        self.events.append(key_event)
        # End with a sync marker
        self.events.append(self.sync_marker(self.timeval))
        # We are done
        self.write_to_pipe(self.events)
693367
def run_workers(no_subprocess, watch_paths=None, is_background=False):
    
    import atexit, os, subprocess, signal
    if watch_paths:
        from watchdog.observers import Observer
        # from watchdog.observers.fsevents import FSEventsObserver as Observer
        # from watchdog.observers.polling import PollingObserver as Observer
        from watchdog.events import FileSystemEventHandler

    def on_modified(event):
        if not is_background:
            print("Restarting worker due to change in %s" % event.src_path)
        log.info("modified %s" % event.src_path)
        try:
            kill_children()
            run_children()
        except:
            log.exception("Error while restarting worker")

    handler = FileSystemEventHandler()
    handler.on_modified = on_modified

    # global child_pids
    child_pids = []
    log.info("starting %s workers" % no_subprocess)

    def run_children():
        global child_pids
        child_pids = []
        for i in range(int(no_subprocess)):
            proc = subprocess.Popen([sys.executable, __file__],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            child_pids.append(proc.pid)
            log.info("Started worker with pid %s" % proc.pid)

    def kill_children():
        """
        kill subprocess on exit of manager (this) process
        """
        log.info("Stopping worker(s)")
        for pid in child_pids:
            if pid is not None:
                os.kill(pid, signal.SIGTERM)

    run_children()
    atexit.register(kill_children)
    signal.signal(signal.SIGTERM, kill_children)
    if watch_paths:
        observer = Observer()
        for path in watch_paths:
            if not is_background:
                print("Watching for changes under %s" % path)
            observer.schedule(handler, path=path, recursive=True)
        observer.start()
    while 1:
        try:
            sleep(1)
        except KeyboardInterrupt:
            log.info("Keyboard interrupt, exiting")
            if watch_paths:
                observer.stop()
                observer.join()
            sys.exit(0)
402855
public synchronized void start() throws IOException {
    Preconditions.checkState(mProcess == null, "Worker is already running");
    mProcess = new ExternalProcess(mProperties, LimitedLifeWorkerProcess.class,
        new File(mLogsDir, "worker.out"));
    mProcess.start();
  }
449604
async def start(self, file_path, locale=None, kwargs=None):
        

        self._file_path = os.path.realpath(file_path)
        self._locale = locale

        if kwargs:
            self._kwargs = kwargs

        if settings.I18N_LIVE_RELOAD:
            loop = asyncio.get_event_loop()

            self._running = True
            self._watcher = aionotify.Watcher()
            self._watcher.watch(
                path=os.path.dirname(self._file_path),
                flags=aionotify.Flags.MOVED_TO | aionotify.Flags.MODIFY,
            )
            await self._watcher.setup(loop)
            await self._load()

            loop.create_task(self._watch())
        else:
            await self._load()
793792
def start(sync_event_source, loop=None):
    """"""

    if not loop:
        loop = asyncio.get_event_loop()

    event_source = asyncio.Queue(loop=loop)

    bridge = threading.Thread(target=_multiprocessing_to_asyncio,
                              args=(sync_event_source, event_source, loop),
                              daemon=True)
    bridge.start()

    app = init_app(event_source, loop=loop)
    aiohttp.web.run_app(app,
                        host=config['wsserver']['host'],
                        port=config['wsserver']['port'])
583982
void start() throws IOException, TooManyListenersException {
        inputStream = port.getInputStream();
        outputStream = port.getOutputStream();
        ReadWorker w = new ReadWorker();
        w.start();
        port.addEventListener(this);
        service.getIdleStatusChecker0().addSession(this);
        try {
            getService().getFilterChainBuilder().buildFilterChain(getFilterChain());
            serviceListeners.fireSessionCreated(this);
        } catch (Throwable e) {
            getFilterChain().fireExceptionCaught(e);
            processor.remove(this);
        }
    }
114831
def run_process(self, slug, inputs):
        """"""
        def export_files(value):
            """Export input files of spawned process."""
            if isinstance(value, str) and os.path.isfile(value):
                # TODO: Use the protocol to export files and get the
                # process schema to check field type.
                print("export {}".format(value))
            elif isinstance(value, dict):
                for item in value.values():
                    export_files(item)
            elif isinstance(value, list):
                for item in value:
                    export_files(item)

        export_files(inputs)
        print('run {}'.format(json.dumps({'process': slug, 'input': inputs}, separators=(',', ':'))))
686099
def start_check (aggregate, out):
    """"""
    # check in background
    t = threading.Thread(target=director.check_urls, args=(aggregate,))
    t.start()
    # time to wait for new data
    sleep_seconds = 2
    # current running time
    run_seconds = 0
    while not aggregate.is_finished():
        yield out.get_data()
        time.sleep(sleep_seconds)
        run_seconds += sleep_seconds
        if run_seconds > MAX_REQUEST_SECONDS:
            director.abort(aggregate)
            break
    yield out.get_data()
1229218
def run(self):
        """"""
        # Create the thread pool.
        executor = concurrent.futures.ThreadPoolExecutor(
            max_workers=self._config['num_workers'])

        # Wait to ensure multiple senders can be synchronised.
        now = int(datetime.datetime.utcnow().timestamp())
        start_time = ((now + 29) // 30) * 30
        self._log.info('Waiting until {}'.format(
                       datetime.datetime.fromtimestamp(start_time)))
        while int(datetime.datetime.utcnow().timestamp()) < start_time:
            time.sleep(0.1)

        # Run the event loop.
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(self._run_loop(executor))
        except KeyboardInterrupt:
            pass
        finally:
            # Send the end of stream message to each stream.
            self._log.info('Shutting down, closing streams...')
            tasks = []
            for stream, item_group in self._streams:
                tasks.append(stream.async_send_heap(item_group.get_end()))
            loop.run_until_complete(asyncio.gather(*tasks))
            self._log.info('... finished.')
            executor.shutdown()
865201
public static void watchFile(String file, SimpleHutoolWatcher watcher, boolean shouldFirstExecute) {
        if (shouldFirstExecute) {
            watcher.doSomething();
        }
        SimpleWatcher simpleWatcher = new SimpleWatcher() {
            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                watcher.onModify(event, currentPath);
                watcher.doSomething();
            }
        };
        try (WatchMonitor monitor = WatchMonitor.createAll(file, simpleWatcher)) {
            monitor.start();
        }
    }
1295197
def startup():
    
    model.setup()
    index.scan_index(config.content_folder)
    index.background_scan(config.content_folder)
880402
def start(self):
        
        for config_class in self.watched_configurables:
            monitor = ConfigFileMonitor(config_class, self.config_dir)
            self.observers.append(
                monitor.start(
                    self.add_configurable,
                    self.update_configurable,
                    self.remove_configurable
                )
            )

        wait_on_event(self.shutdown)