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.
5 #ifndef CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_
6 #define CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_
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"
18 namespace safe_browsing
{
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
{
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();
33 // Registers |callback| with the runner. A copy of |callback| is held until it
35 void RegisterCallback(const base::Closure
& callback
);
37 // Starts running the callbacks after the delay.
41 typedef std::list
<base::Closure
> CallbackList
;
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.
47 base::ThreadChecker thread_checker_
;
49 // The runner on which callbacks are to be run.
50 scoped_refptr
<base::TaskRunner
> task_runner_
;
52 // The list of callbacks to run. Callbacks are removed when run.
53 CallbackList callbacks_
;
55 // callbacks_.end() when no work is being done. Any other value otherwise.
56 CallbackList::iterator next_callback_
;
58 // A timer upon the firing of which the next callback will be run.
59 base::DelayTimer
<DelayedCallbackRunner
> timer_
;
61 DISALLOW_COPY_AND_ASSIGN(DelayedCallbackRunner
);
64 } // namespace safe_browsing
66 #endif // CHROME_BROWSER_SAFE_BROWSING_INCIDENT_REPORTING_DELAYED_CALLBACK_RUNNER_H_