Chromium Code Reviews| Index: chrome/browser/safe_browsing/delayed_callback_runner.cc |
| diff --git a/chrome/browser/safe_browsing/delayed_callback_runner.cc b/chrome/browser/safe_browsing/delayed_callback_runner.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..93f78c1ea4e5fa2ce78cba84e419824e32a304a2 |
| --- /dev/null |
| +++ b/chrome/browser/safe_browsing/delayed_callback_runner.cc |
| @@ -0,0 +1,70 @@ |
| +// Copyright 2014 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +#include "chrome/browser/safe_browsing/delayed_callback_runner.h" |
| + |
| +#include "base/location.h" |
| +#include "base/single_thread_task_runner.h" |
| +#include "base/thread_task_runner_handle.h" |
| + |
| +namespace { |
| + |
| +// Runs |callback| on the thread to which |thread_runner| belongs. The callback |
| +// is run immediately if this function is called on |thread_runner|'s thread. |
| +void RunCallbackOnOriginThread( |
| + const base::Closure& callback, |
| + scoped_refptr<base::SingleThreadTaskRunner> thread_runner) { |
| + if (thread_runner->BelongsToCurrentThread()) |
| + callback.Run(); |
| + else |
| + thread_runner->PostTask(FROM_HERE, callback); |
| +} |
| + |
| +} // namespace |
| + |
| +namespace safe_browsing { |
| + |
| +DelayedCallbackRunner::DelayedCallbackRunner( |
| + base::TimeDelta delay, |
| + scoped_refptr<base::TaskRunner> task_runner) |
| + : task_runner_(task_runner), |
| + next_callback_(callbacks_.end()), |
| + timer_(FROM_HERE, delay, this, &DelayedCallbackRunner::OnTimer) { |
| +} |
| + |
| +DelayedCallbackRunner::~DelayedCallbackRunner() { |
| +} |
| + |
| +void DelayedCallbackRunner::RegisterCallback(const base::Closure& callback) { |
| + DCHECK(thread_checker_.CalledOnValidThread()); |
| + callbacks_.push_back(base::Bind(&RunCallbackOnOriginThread, |
|
grt (UTC plus 2)
2014/08/04 14:16:29
oops, this is totally wrong.
|
| + callback, |
| + base::ThreadTaskRunnerHandle::Get())); |
| +} |
| + |
| +void DelayedCallbackRunner::Start() { |
| + DCHECK(thread_checker_.CalledOnValidThread()); |
| + |
| + // Nothing to do if the runner is already running or nothing has been added. |
| + if (next_callback_ != callbacks_.end() || callbacks_.empty()) |
| + return; |
| + |
| + // Prime the system with the first callback. |
| + next_callback_ = callbacks_.begin(); |
| + |
| + // Point the starter pistol in the air and pull the trigger. |
| + timer_.Reset(); |
| +} |
| + |
| +void DelayedCallbackRunner::OnTimer() { |
| + // Run the next callback on the task runner. |
| + task_runner_->PostTask(FROM_HERE, *next_callback_); |
| + |
| + // Remove this callback and get ready for the next if there is one. |
| + next_callback_ = callbacks_.erase(next_callback_); |
| + if (next_callback_ != callbacks_.end()) |
| + timer_.Reset(); |
| +} |
| + |
| +} // namespace safe_browsing |