## watcher.run(throttle)
Uses RAF to monitor breakpoint changes.
497281
function () {
        function checkUpdate() {
            var current = module.exports.current();
            if (current !== last) {
                last = current;
                events.trigger('update', current);
            }
        }

        // Do not run unless breakpoints are available.
        if (!running && breakpoints.length) {
            running = true;
            global.addEventListener('resize', function () {
                if (!working) {
                    working = true;
                    global.requestAnimationFrame(function () {
                        checkUpdate();
                        working = false;
                    });
                }
            });
        }
        checkUpdate();
    }
1207530
function(app, opts) {
  this.app = app;
  this.handlerMap = {};
  if(!!opts.reloadHandlers) {
    watchHandlers(app, this.handlerMap);
  }

  this.enableForwardLog = opts.enableForwardLog || false;
}
161314
private void sawMonitorEnter(int pc) {
        monitorSyncPCs.add(Integer.valueOf(pc));

        ScopeBlock sb = new ScopeBlock(pc, Integer.MAX_VALUE);
        sb.setSync();
        rootScopeBlock.addChild(sb);
    }
497559
def watch(logger_name, level=DEBUG, out=stdout):
    
    watcher = Watcher(logger_name)
    watcher.watch(level, out)
    return watcher
423056
async def start_child():
    

    logger.info('Started to watch for code changes')

    loop = asyncio.get_event_loop()
    watcher = aionotify.Watcher()

    flags = (
        aionotify.Flags.MODIFY |
        aionotify.Flags.DELETE |
        aionotify.Flags.ATTRIB |
        aionotify.Flags.MOVED_TO |
        aionotify.Flags.MOVED_FROM |
        aionotify.Flags.CREATE |
        aionotify.Flags.DELETE_SELF |
        aionotify.Flags.MOVE_SELF
    )

    watched_dirs = list_dirs()

    for dir_name in watched_dirs:
        watcher.watch(path=dir_name, flags=flags)

    await watcher.setup(loop)

    while True:
        evt = await watcher.get_event()
        file_path = path.join(evt.alias, evt.name)

        if file_path in watched_dirs or file_path.endswith('.py'):
            await asyncio.sleep(settings.CODE_RELOAD_DEBOUNCE)
            break

    watcher.close()
    exit_for_reload()
635755
private void processWatcher(MethodSpec.Builder createdMethodBuilder, ExecutableElement method) {
    Watch watch = method.getAnnotation(Watch.class);

    String exposedMethodName = exposeExistingJavaMethodToJs(method);
    String watcherTriggerMethodName = addNewMethodToProto();

    MethodSpec.Builder watcherMethodBuilder = MethodSpec
        .methodBuilder(watcherTriggerMethodName)
        .addModifiers(Modifier.PUBLIC)
        .addAnnotation(JsMethod.class)
        .returns(Object.class);

    String[] valueSplit = watch.value().split("\\.");

    String currentExpression = "";
    for (int i = 0; i < valueSplit.length - 1; i++) {
      currentExpression += valueSplit[i];
      watcherMethodBuilder.addStatement("if ($L == null) return null", currentExpression);
      currentExpression += ".";
    }

    watcherMethodBuilder.addStatement("return $L", watch.value());

    componentExposedTypeBuilder.addMethod(watcherMethodBuilder.build());

    createdMethodBuilder
        .addStatement("vue().$L(p.$L, p.$L, $T.of($L, $L))", "$watch",
            watcherTriggerMethodName, exposedMethodName, WatchOptions.class, watch.isDeep(),
            watch.isImmediate());
  }
588187
def start_watchers
      # Watcher callbacks are invoked in a separate Ruby thread. Note that there
      # is a possible deadlock between invoking watcher callbacks and calling
      # close(): if we get a watcher event and a close at around the same time,
      # the close might fire first. Closing the Zk handle will block on
      # dispatching outstanding watchers, but it does so holding the @zk_mutex,
      # causing a deadlock. Hence, we just have the watcher callback spin on the
      # @zk_mutex, aborting if the handle is ever closed.
      @child_watcher = Zookeeper::Callbacks::WatcherCallback.new do
        while true
          break if @zk.closed?
          if @zk_mutex.try_lock
            get_and_watch unless @zk.closed?
            @zk_mutex.unlock
            break
          end
        end
      end

      @stat_watcher = Zookeeper::Callbacks::WatcherCallback.new do
        while true
          break if @zk.closed?
          if @zk_mutex.try_lock
            stat_and_watch unless @zk.closed?
            @zk_mutex.unlock
            break
          end
        end
      end

      stat_and_watch
    end
49246
private void watchFilesTask() {
        while (!watcherExecutor.isShutdown()) {
            try {
                WatchKey key = watchService.take();
                Path parent = watchKeyDirs.get(key);
                if (parent == null) {
                    key.reset();
                    continue;
                }

                Set<Path> updates = new TreeSet<>();
                for (WatchEvent<?> ev : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = ev.kind();

                    // Only file modification, creation, deletion is interesting.
                    if (kind != ENTRY_MODIFY &&
                        kind != ENTRY_CREATE &&
                        kind != ENTRY_DELETE) {
                        if (kind == OVERFLOW) {
                            LOGGER.warn("Overflow event, file updates may have been lost");
                        }
                        continue;
                    }

                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> event = (WatchEvent<Path>) ev;

                    Path file = parent.resolve(event.context());
                    if (targetToRequests.containsKey(file)) {
                        LOGGER.trace("Watched file " + file + " event " + kind);
                        updates.add(file);
                    }
                }
                // Ready the key again so it wil signal more events.
                key.reset();

                if (updates.size() > 0) {
                    List<Supplier<Listener>>           watcherList;
                    Map<Path,List<Supplier<Listener>>> watcherMap;
                    Set<Path>                          updatedRequests = new TreeSet<>();
                    synchronized (mutex) {
                        watcherList = new ArrayList<>(this.watchers);
                        watcherMap = deepCopy(watchedFiles);

                        for (final Path file : updates) {
                            updatedRequests.addAll(targetToRequests.getOrDefault(file, Collections.emptySet()));
                        }
                        for (final Path file : updates) {
                            try {
                                updateLinkTargetting(file);
                            } catch (IOException e) {
                                LOGGER.warn("Failed to update link targeting: {}", e.getMessage(), e);
                            }
                        }
                    }

                    callbackExecutor.submit(() -> {
                        for (final Path file : updates) {
                            for (final Supplier<Listener> supplier : watcherList) {
                                Listener watcher = supplier.get();
                                if (watcher != null) {
                                    try {
                                        watcher.onPathUpdate(file);
                                    } catch (RuntimeException e) {
                                        LOGGER.error("Exception when notifying update on " + file, e);
                                    }
                                }
                            }
                        }
                        for (Path request : updatedRequests) {
                            Optional.ofNullable(watcherMap.get(request))
                                    .ifPresent(list -> {
                                        for (final Supplier<Listener> supplier : list) {
                                            Listener watcher = supplier.get();
                                            if (watcher != null) {
                                                try {
                                                    watcher.onPathUpdate(request);
                                                } catch (RuntimeException e) {
                                                    LOGGER.error("Exception when notifying update on " + request, e);
                                                }
                                            }
                                        }
                                    });
                        }
                    });
                }
            } catch (InterruptedException interruptedEx) {
                LOGGER.error("Interrupted in service file watch thread: " + interruptedEx.getMessage(), interruptedEx);
                return;
            }
        }
    }
1299730
function watch() {
  gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, inline, browser.reload));
  gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('all', gulp.series(resetPages, pages, inline, browser.reload));
  gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('all', gulp.series(resetPages, sass, pages, inline, browser.reload));
  gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload));
}
1295960
private void ensureWatchThreadRunning() {
		if (!threadRunning) {
			thread = new Thread(watchThread);
			thread.setDaemon(true);
			thread.start();
			watchThread.setThread(thread);
			watchThread.updateName();
			threadRunning = true;
		}
	}
204824
function (getterSetter, context, callback, computeState) {
            // track what we are observing
            var observing = {},
                // a flag indicating if this observe/attr pair is already bound
                matched = true,
                // the data to return
                data = {
                    // we will maintain the value while live-binding is taking place
                    value: undefined,
                    // a teardown method that stops listening
                    teardown: function () {
                        for (var name in observing) {
                            var ob = observing[name];
                            ob.observe.obj.unbind(ob.observe.attr, onchanged);
                            delete observing[name];
                        }
                    }
                },
                batchNum;

            // when a property value is changed
            var onchanged = function (ev) {
                // If the compute is no longer bound (because the same change event led to an unbind)
                // then do not call getValueAndBind, or we will leak bindings.
                if (computeState && !computeState.bound) {
                    return;
                }
                if (ev.batchNum === undefined || ev.batchNum !== batchNum) {
                    // store the old value
                    var oldValue = data.value,
                        // get the new value
                        newvalue = getValueAndBind();
                    // update the value reference (in case someone reads)
                    data.value = newvalue;
                    // if a change happened
                    if (newvalue !== oldValue) {
                        callback(newvalue, oldValue);
                    }
                    batchNum = batchNum = ev.batchNum;
                }


            };

            // gets the value returned by `getterSetter` and also binds to any attributes
            // read by the call
            var getValueAndBind = function () {
                var info = getValueAndObserved(getterSetter, context),
                    newObserveSet = info.observed;

                var value = info.value;
                matched = !matched;

                // go through every attribute read by this observe
                can.each(newObserveSet, function (ob) {
                    // if the observe/attribute pair is being observed
                    if (observing[ob.obj._cid + "|" + ob.attr]) {
                        // mark at as observed
                        observing[ob.obj._cid + "|" + ob.attr].matched = matched;
                    } else {
                        // otherwise, set the observe/attribute on oldObserved, marking it as being observed
                        observing[ob.obj._cid + "|" + ob.attr] = {
                            matched: matched,
                            observe: ob
                        };
                        ob.obj.bind(ob.attr, onchanged);
                    }
                });

                // Iterate through oldObserved, looking for observe/attributes
                // that are no longer being bound and unbind them
                for (var name in observing) {
                    var ob = observing[name];
                    if (ob.matched !== matched) {
                        ob.observe.obj.unbind(ob.observe.attr, onchanged);
                        delete observing[name];
                    }
                }
                return value;
            };
            // set the initial value
            data.value = getValueAndBind();
            data.isListening = !can.isEmptyObject(observing);
            return data;
        }
608938
def watch_and_run(monitor, times, recursively, directory, *flags)
      result = OpenStruct.new(directory: directory, changes: [])
      i = 0
      result.changes[i] = OpenStruct.new(called: false)
      can_return = false
      callback = Proc.new do |change|
        next if can_return

        result.changes[i].called = true;
        result.changes[i].change = change

        i += 1

        if i < times
          result.changes[i] = OpenStruct.new(called: false)
        else
          can_return = true
        end
      end

      if recursively
        monitor.watch_recursively(directory, *flags, &callback)
      else
        monitor.watch(directory, *flags, &callback)
      end

      thread = Thread.new(monitor) { |m| m.run! }
      sleep(0.2) # give time for the monitor to bootup

      yield # So much boilerplate code to get here :S

      sleep(0.2) # allow the monitor to run the callbacks

      # Nothing can change after the callback if there is only one of them,
      # so never wait for one callback
      if times > 1
        until can_return
          sleep(0.1)
        end
      end

      return result
    ensure
      monitor.stop
      thread.join if thread
    end
1037500
function() {

        // Don't continue if the probe portion was what changed.
        var thisMonitor = JSON.stringify(monitor.toMonitorJSON());
        if (thisMonitor === t.priorMonitor) {
          return;
        }

        // Remove the component listeners
        log.info('render.monitorChange', t.logCtxt);
        component.off('change:css change:viewOptions', applyStyles);
        component.off('change:monitor', onMonitorChange, t);

        // Disconnect, then build a fresh component
        t.connectMonitor(false, function(){
          UI.pageView.removeComponent(t.model);
          UI.pageView.addComponent(t.model);
        });
      }
1340253
def stopObserver(self):
        
        self._observer.isStopped = True
        self._observer.isRunning = False
1261555
public void onFileChange(File file) {
        mojo.getLog().info(EMPTY_STRING);
        mojo.getLog().info("The watcher has detected a change in " + file.getAbsolutePath());
        mojo.getLog().info(EMPTY_STRING);
        for (Watcher watcher : watchers) {
            if (watcher.accept(file)) {
                cleanupErrorFile(watcher);
                // This flag will be set to false if the processing must be interrupted.
                boolean continueProcessing;
                try {
                    continueProcessing = watcher.fileUpdated(file);
                } catch (WatchingException e) { //NOSONAR
                    mojo.getLog().debug(watcher + " has thrown an exception while handling the " + file.getName() + EMPTY_STRING +
                            " update", e);
                    mojo.getLog().error(String.format(WATCHING_EXCEPTION_MESSAGE, e.getMessage()));
                    createErrorFile(watcher, e);
                    continueProcessing = false;
                }
                if (!continueProcessing) {
                    break;
                }
            }
        }
        mojo.getLog().info(EMPTY_STRING);
        mojo.getLog().info(EMPTY_STRING);
    }
859328
function () {
            /*  determine parameters  */
            var params = $cs.params("observe", arguments, {
                name:        { pos: 0, req: true,   valid: "string"        },
                func:        { pos: 1, req: true,   valid: "function"      },
                touch:       {         def: false,  valid: "boolean"       },
                boot:        {         def: false,  valid: "boolean"       },
                op:          {         def: "set",  valid: /^(?:get|set|changed|splice|delete)$/ },
                spool:       {         def: null,   valid: "(null|string)" },
                noevent:     {         def: false,  valid: "boolean"       }
            });

            /*  parse the value name into selection path segments  */
            var path = _cs.select_parse(params.name);

            /*  determine the actual component owning the model
                as we want to subscribe the change event there only  */
            var owner = null;
            var model = null;
            var comp  = this;
            while (comp !== null) {
                owner = comp.property({ name: "ComponentJS:model", returnowner: true });
                if (!_cs.isdefined(owner))
                    throw _cs.exception("observe", "no model found containing value \"" + path[0] + "\"");
                model = owner.property("ComponentJS:model");
                if (_cs.isdefined(model.spec[path[0]]))
                    break;
                comp = owner.parent();
            }
            if (comp === null)
                throw _cs.exception("observe", "no model found containing value \"" + path[0] + "\"");

            /*  support wildcard matching and always match childs  */
            var name = path.join(".")
                .replace(/\./g, "\\.")
                .replace(/\*\*/g, ".+?")
                .replace(/\*/g, "[^.]+");
            name += "(?:\\.[^.]+)*";

            /*  subscribe to model value change event  */
            var id = owner.subscribe({
                name:      new RegExp("ComponentJS:model:" + name + ":" + params.op),
                capturing: false,
                spreading: false,
                bubbling:  false,
                noevent:   params.noevent,
                func:      params.func
            });

            /*  mark component for having subscribers of operation
                (for performance optimization reasons)  */
            var key = "ComponentJS:model:subscribers:" + params.op;
            var subscribers = owner.property({ name: key, def: 0 });
            subscribers += 1;
            owner.property({ name: key, value: subscribers });

            /*  optionally spool reverse operation  */
            if (params.spool !== null) {
                var info = _cs.spool_spec_parse(this, params.spool);
                info.comp.spool(info.name, this, "unobserve", id);
            }

            /*  if requested (for a one-time initial observer run),
                either touch the model value once (which causes _all_ observers to trigger!)
                or do a "bootstrapping execution" of only our callback function once  */
            if (params.touch)
                this.touch(params.name);
            else if (params.boot) {
                var value = this.value(params.name);
                var args = [ value, value, params.op, path.join(".") ];
                if (!params.noevent) {
                    args.unshift($cs.event({
                        name:        params.name,
                        spec:        {},
                        async:       false,
                        result:      undefined,
                        target:      this,
                        propagation: true,
                        processing:  true,
                        dispatched:  false
                    }));
                }
                params.func.apply(this, args);
            }

            return id;
        }
868439
function watchChanges(io, params) {
    const folder = process.cwd();
    return watch(folder, { recursive: true }, () => {
        emitInfo('changes detected. Recompiling...');
        io.sockets.emit('load');
        const start = new Date().getTime();
        executeWithParams(params)
            .tap(alerts => {
                const ellapsed = new Date().getTime() - start;
                emitSuccess(`wow! recompiled and executed in ${ellapsed}ms!`);
                io.sockets.emit('update', compileMarkdown(alerts));
            })
            .catch(err => {
                emitError(`hot compilation error, baby: ${err.message}`);
                io.sockets.emit('failure', err.stack);
            });
    });
}