metrics_scheduler.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_METRICS_METRICS_SCHEDULER_H_
  5. #define COMPONENTS_METRICS_METRICS_SCHEDULER_H_
  6. #include "base/callback.h"
  7. #include "base/time/time.h"
  8. #include "base/timer/timer.h"
  9. namespace metrics {
  10. // Scheduler task to drive a MetricsService object's uploading.
  11. class MetricsScheduler {
  12. public:
  13. // Creates MetricsScheduler object with the given |task_callback|
  14. // callback to call when a task should happen.
  15. MetricsScheduler(const base::RepeatingClosure& task_callback,
  16. bool fast_startup_for_testing);
  17. MetricsScheduler(const MetricsScheduler&) = delete;
  18. MetricsScheduler& operator=(const MetricsScheduler&) = delete;
  19. virtual ~MetricsScheduler();
  20. // Starts scheduling uploads. This in a no-op if the scheduler is already
  21. // running, so it is safe to call more than once.
  22. void Start();
  23. // Stops scheduling uploads.
  24. void Stop();
  25. protected:
  26. // Subclasses should provide task_callback with a wrapper to call this with.
  27. // This indicates the triggered task was completed/cancelled and the next
  28. // call can be scheduled.
  29. void TaskDone(base::TimeDelta next_interval);
  30. // Called by the Timer when it's time to run the task.
  31. virtual void TriggerTask();
  32. private:
  33. // Schedules a future call to TriggerTask if one isn't already pending.
  34. void ScheduleNextTask();
  35. // The method to call when task should happen.
  36. const base::RepeatingClosure task_callback_;
  37. // Uses a one-shot timer rather than a repeating one because the task may be
  38. // async, and the length of the interval may change.
  39. base::OneShotTimer timer_;
  40. // The interval between being told an task is done and starting the next task.
  41. base::TimeDelta interval_;
  42. // Indicates that the scheduler is running (i.e., that Start has been called
  43. // more recently than Stop).
  44. bool running_;
  45. // Indicates that the last triggered task hasn't resolved yet.
  46. bool callback_pending_;
  47. };
  48. } // namespace metrics
  49. #endif // COMPONENTS_METRICS_METRICS_SCHEDULER_H_