1 // Copyright (c) 2012 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 #include "chrome/common/worker_thread_ticker.h"
10 #include "base/bind_helpers.h"
11 #include "base/location.h"
12 #include "base/logging.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/threading/thread.h"
16 WorkerThreadTicker::WorkerThreadTicker(int tick_interval
)
17 : timer_thread_("worker_thread_ticker"),
19 tick_interval_(base::TimeDelta::FromMilliseconds(tick_interval
)) {
22 WorkerThreadTicker::~WorkerThreadTicker() {
26 bool WorkerThreadTicker::RegisterTickHandler(Callback
*tick_handler
) {
28 base::AutoLock
lock(lock_
);
29 // You cannot change the list of handlers when the timer is running.
30 // You need to call Stop first.
33 tick_handler_list_
.push_back(tick_handler
);
37 bool WorkerThreadTicker::UnregisterTickHandler(Callback
*tick_handler
) {
39 base::AutoLock
lock(lock_
);
40 // You cannot change the list of handlers when the timer is running.
41 // You need to call Stop first.
45 TickHandlerListType::iterator index
= std::remove(tick_handler_list_
.begin(),
46 tick_handler_list_
.end(),
48 if (index
== tick_handler_list_
.end()) {
51 tick_handler_list_
.erase(index
, tick_handler_list_
.end());
55 bool WorkerThreadTicker::Start() {
56 // Do this in a lock because we don't want 2 threads to
57 // call Start at the same time
58 base::AutoLock
lock(lock_
);
61 if (!timer_thread_
.Start())
68 bool WorkerThreadTicker::Stop() {
69 // Do this in a lock because we don't want 2 threads to
70 // call Stop at the same time
71 base::AutoLock
lock(lock_
);
79 void WorkerThreadTicker::ScheduleTimerTask() {
80 timer_thread_
.task_runner()->PostDelayedTask(
82 base::Bind(&WorkerThreadTicker::TimerTask
, base::Unretained(this)),
86 void WorkerThreadTicker::TimerTask() {
87 // When the ticker is running, the handler list CANNOT be modified.
88 // So we can do the enumeration safely without a lock
89 const TickHandlerListType
& handlers
= tick_handler_list_
;
90 for (TickHandlerListType::const_iterator i
= handlers
.begin();
91 i
!= handlers
.end(); ++i
) {