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