Example #1
0
bool startObservingFile(const std::string& filePath,
                        folly::EventBase& evb,
                        uint32_t pollPeriodMs,
                        uint32_t sleepBeforeUpdateMs,
                        std::function<void(std::string)> onUpdate,
                        std::function<void()> fallbackOnError) {

  std::shared_ptr<FileDataProvider> provider;
  try {
    provider = std::make_shared<FileDataProvider>(filePath);

    onUpdate(provider->load());
  } catch (const std::exception& e) {
    VLOG(0) << "Can not start watching " << filePath <<
               " for modifications: " << e.what();
    checkAndExecuteFallbackOnError(std::move(fallbackOnError));
    return false;
  }

  VLOG(0) << "Watching " << filePath << " for modifications.";
  FileObserverData data(std::move(provider),
                        std::move(onUpdate),
                        std::move(fallbackOnError),
                        pollPeriodMs,
                        sleepBeforeUpdateMs);
  return evb.runInEventBaseThread([&evb, data = std::move(data)]() {
    scheduleObserveFile(evb, std::move(data));
  });
}
bool FileObserver::startObserving(const std::string& filePath,
                                  PeriodicTaskScheduler& taskScheduler,
                                  uint32_t pollPeriodMs,
                                  uint32_t sleepBeforeUpdateMs,
                                  std::function<void(std::string)> onUpdate,
                                  std::function<void()> fallbackOnError) 
{
  std::shared_ptr<FileDataProvider> provider;
  try {
    provider = std::make_shared<FileDataProvider>(filePath);

    onUpdate(provider->load());
  } catch (const std::exception& e) {
    VLOG(0) << "Can not start watching " << filePath <<
               " for modifications: " << e.what();
    checkAndExecuteFallbackOnError(fallbackOnError);
    return false;
  }

  VLOG(0) << "Watching " << filePath << " for modifications.";
  taskScheduler.scheduleTask(
    /* tmo_ms = */ pollPeriodMs,
    [onUpdate, fallbackOnError, sleepBeforeUpdateMs, provider]
    (PeriodicTaskScheduler& scheduler)
	{
      try {
        if (!provider->hasUpdate()) {
          return;
        }

        scheduler.sleepThread(sleepBeforeUpdateMs);
        onUpdate(provider->load());
      } catch (...) {
        checkAndExecuteFallbackOnError(fallbackOnError);
        throw;
      }
    }
  );
  return true;
}