1 // Copyright 2014 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 5 #ifndef CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_ 6 #define CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_ 7 8 #include <list> 9 10 #include "base/callback_forward.h" 11 #include "base/macros.h" 12 #include "base/memory/ref_counted.h" 13 #include "base/task_runner.h" 14 #include "base/threading/thread_checker.h" 15 #include "base/time/time.h" 16 #include "base/timer/timer.h" 17 18 namespace safe_browsing { 19 20 // Runs callbacks on a given task runner, waiting a certain amount of time 21 // between each. The delay also applies to running the first callback (i.e., 22 // the first callback will be run some time after Start() is invoked). Callbacks 23 // are deleted after they are run. Start() is idempotent: calling it while the 24 // runner is doing its job has no effect. 25 class DelayedCallbackRunner { 26 public: 27 // Constructs an instance that runs tasks on |callback_runner|, waiting for 28 // |delay| time to pass before and between each callback. 29 DelayedCallbackRunner(base::TimeDelta delay, 30 const scoped_refptr<base::TaskRunner>& task_runner); 31 ~DelayedCallbackRunner(); 32 33 // Registers |callback| with the runner. A copy of |callback| is held until it 34 // is run. 35 void RegisterCallback(const base::Closure& callback); 36 37 // Starts running the callbacks after the delay. 38 void Start(); 39 40 private: 41 typedef std::list<base::Closure> CallbackList; 42 43 // A callback invoked by the timer to run the next callback. The timer is 44 // restarted to process the next callback if there is one. 45 void OnTimer(); 46 47 base::ThreadChecker thread_checker_; 48 49 // The runner on which callbacks are to be run. 50 scoped_refptr<base::TaskRunner> task_runner_; 51 52 // The list of callbacks to run. Callbacks are removed when run. 53 CallbackList callbacks_; 54 55 // callbacks_.end() when no work is being done. Any other value otherwise. 56 CallbackList::iterator next_callback_; 57 58 // A timer upon the firing of which the next callback will be run. 59 base::DelayTimer<DelayedCallbackRunner> timer_; 60 61 DISALLOW_COPY_AND_ASSIGN(DelayedCallbackRunner); 62 }; 63 64 } // namespace safe_browsing 65 66 #endif // CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_ 67