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/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/threading/thread.h"
15 WorkerThreadTicker::WorkerThreadTicker(int tick_interval
)
16 : timer_thread_("worker_thread_ticker"),
18 tick_interval_(base::TimeDelta::FromMilliseconds(tick_interval
)) {
21 WorkerThreadTicker::~WorkerThreadTicker() {
25 bool WorkerThreadTicker::RegisterTickHandler(Callback
*tick_handler
) {
27 base::AutoLock
lock(lock_
);
28 // You cannot change the list of handlers when the timer is running.
29 // You need to call Stop first.
32 tick_handler_list_
.push_back(tick_handler
);
36 bool WorkerThreadTicker::UnregisterTickHandler(Callback
*tick_handler
) {
38 base::AutoLock
lock(lock_
);
39 // You cannot change the list of handlers when the timer is running.
40 // You need to call Stop first.
44 TickHandlerListType::iterator index
= std::remove(tick_handler_list_
.begin(),
45 tick_handler_list_
.end(),
47 if (index
== tick_handler_list_
.end()) {
50 tick_handler_list_
.erase(index
, tick_handler_list_
.end());
54 bool WorkerThreadTicker::Start() {
55 // Do this in a lock because we don't want 2 threads to
56 // call Start at the same time
57 base::AutoLock
lock(lock_
);
60 if (!timer_thread_
.Start())
67 bool WorkerThreadTicker::Stop() {
68 // Do this in a lock because we don't want 2 threads to
69 // call Stop at the same time
70 base::AutoLock
lock(lock_
);
78 void WorkerThreadTicker::ScheduleTimerTask() {
79 timer_thread_
.message_loop()->PostDelayedTask(
81 base::Bind(&WorkerThreadTicker::TimerTask
, base::Unretained(this)),
85 void WorkerThreadTicker::TimerTask() {
86 // When the ticker is running, the handler list CANNOT be modified.
87 // So we can do the enumeration safely without a lock
88 const TickHandlerListType
& handlers
= tick_handler_list_
;
89 for (TickHandlerListType::const_iterator i
= handlers
.begin();
90 i
!= handlers
.end(); ++i
) {