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#include "chrome/browser/safe_browsing/incident_reporting/delayed_callback_runner.h"
6
7#include "base/location.h"
8
9namespace safe_browsing {
10
11DelayedCallbackRunner::DelayedCallbackRunner(
12    base::TimeDelta delay,
13    const scoped_refptr<base::TaskRunner>& task_runner)
14    : task_runner_(task_runner),
15      next_callback_(callbacks_.end()),
16      timer_(FROM_HERE, delay, this, &DelayedCallbackRunner::OnTimer) {
17}
18
19DelayedCallbackRunner::~DelayedCallbackRunner() {
20}
21
22void DelayedCallbackRunner::RegisterCallback(const base::Closure& callback) {
23  DCHECK(thread_checker_.CalledOnValidThread());
24  callbacks_.push_back(callback);
25}
26
27void DelayedCallbackRunner::Start() {
28  DCHECK(thread_checker_.CalledOnValidThread());
29
30  // Nothing to do if the runner is already running or nothing has been added.
31  if (next_callback_ != callbacks_.end() || callbacks_.empty())
32    return;
33
34  // Prime the system with the first callback.
35  next_callback_ = callbacks_.begin();
36
37  // Point the starter pistol in the air and pull the trigger.
38  timer_.Reset();
39}
40
41void DelayedCallbackRunner::OnTimer() {
42  // Run the next callback on the task runner.
43  task_runner_->PostTask(FROM_HERE, *next_callback_);
44
45  // Remove this callback and get ready for the next if there is one.
46  next_callback_ = callbacks_.erase(next_callback_);
47  if (next_callback_ != callbacks_.end())
48    timer_.Reset();
49}
50
51}  // namespace safe_browsing
52