Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(34)

Side by Side Diff: base/timer/timer.h

Issue 2491613004: Make base::Timer sequence-friendly. (Closed)
Patch Set: add back commented out DCHECK in Stop() Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | base/timer/timer.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // OneShotTimer and RepeatingTimer provide a simple timer API. As the names 5 // OneShotTimer and RepeatingTimer provide a simple timer API. As the names
6 // suggest, OneShotTimer calls you back once after a time delay expires. 6 // suggest, OneShotTimer calls you back once after a time delay expires.
7 // RepeatingTimer on the other hand calls you back periodically with the 7 // RepeatingTimer on the other hand calls you back periodically with the
8 // prescribed time interval. 8 // prescribed time interval.
9 // 9 //
10 // OneShotTimer and RepeatingTimer both cancel the timer when they go out of 10 // OneShotTimer and RepeatingTimer both cancel the timer when they go out of
(...skipping 17 matching lines...) Expand all
28 // void DoStuff() { 28 // void DoStuff() {
29 // // This method is called every second to do stuff. 29 // // This method is called every second to do stuff.
30 // ... 30 // ...
31 // } 31 // }
32 // base::RepeatingTimer timer_; 32 // base::RepeatingTimer timer_;
33 // }; 33 // };
34 // 34 //
35 // Both OneShotTimer and RepeatingTimer also support a Reset method, which 35 // Both OneShotTimer and RepeatingTimer also support a Reset method, which
36 // allows you to easily defer the timer event until the timer delay passes once 36 // allows you to easily defer the timer event until the timer delay passes once
37 // again. So, in the above example, if 0.5 seconds have already passed, 37 // again. So, in the above example, if 0.5 seconds have already passed,
38 // calling Reset on timer_ would postpone DoStuff by another 1 second. In 38 // calling Reset on |timer_| would postpone DoStuff by another 1 second. In
39 // other words, Reset is shorthand for calling Stop and then Start again with 39 // other words, Reset is shorthand for calling Stop and then Start again with
40 // the same arguments. 40 // the same arguments.
41 // 41 //
42 // NOTE: These APIs are not thread safe. Always call from the same thread. 42 // These APIs are not thread safe. All methods must be called from the same
43 // sequence (not necessarily the construction sequence), except for the
44 // destructor and SetTaskRunner() which may be called from any sequence when the
45 // timer is not running (i.e. when Start() has never been called or Stop() has
46 // been called since the last Start()). By default, the scheduled tasks will be
47 // run on the same sequence that the Timer was *started on*, but this can be
48 // changed *prior* to Start() via SetTaskRunner().
43 49
44 #ifndef BASE_TIMER_TIMER_H_ 50 #ifndef BASE_TIMER_TIMER_H_
45 #define BASE_TIMER_TIMER_H_ 51 #define BASE_TIMER_TIMER_H_
46 52
47 // IMPORTANT: If you change timer code, make sure that all tests (including 53 // IMPORTANT: If you change timer code, make sure that all tests (including
48 // disabled ones) from timer_unittests.cc pass locally. Some are disabled 54 // disabled ones) from timer_unittests.cc pass locally. Some are disabled
49 // because they're flaky on the buildbot, but when you run them locally you 55 // because they're flaky on the buildbot, but when you run them locally you
50 // should be able to tell the difference. 56 // should be able to tell the difference.
51 57
52 #include <memory> 58 #include <memory>
53 59
54 #include "base/base_export.h" 60 #include "base/base_export.h"
55 #include "base/bind.h" 61 #include "base/bind.h"
56 #include "base/bind_helpers.h" 62 #include "base/bind_helpers.h"
57 #include "base/callback.h" 63 #include "base/callback.h"
58 #include "base/location.h" 64 #include "base/location.h"
59 #include "base/macros.h" 65 #include "base/macros.h"
66 #include "base/sequence_checker_impl.h"
67 #include "base/sequenced_task_runner.h"
60 #include "base/time/time.h" 68 #include "base/time/time.h"
61 69
62 namespace base { 70 namespace base {
63 71
64 class BaseTimerTaskInternal; 72 class BaseTimerTaskInternal;
65 class SingleThreadTaskRunner;
66 class TickClock; 73 class TickClock;
67 74
75 // TODO(gab): Removing this fwd-decl causes IWYU failures in other headers,
76 // remove it in a follow- up CL.
77 class SingleThreadTaskRunner;
78
68 //----------------------------------------------------------------------------- 79 //-----------------------------------------------------------------------------
69 // This class wraps MessageLoop::PostDelayedTask to manage delayed and repeating 80 // This class wraps TaskRunner::PostDelayedTask to manage delayed and repeating
70 // tasks. It must be destructed on the same thread that starts tasks. There are 81 // tasks. See meta comment above for thread-safety requirements.
71 // DCHECKs in place to verify this.
72 // 82 //
73 class BASE_EXPORT Timer { 83 class BASE_EXPORT Timer {
74 public: 84 public:
75 // Construct a timer in repeating or one-shot mode. Start or SetTaskInfo must 85 // Construct a timer in repeating or one-shot mode. Start must be called later
76 // be called later to set task info. |retain_user_task| determines whether the 86 // to set task info. |retain_user_task| determines whether the user_task is
77 // user_task is retained or reset when it runs or stops. If |tick_clock| is 87 // retained or reset when it runs or stops. If |tick_clock| is provided, it is
78 // provided, it is used instead of TimeTicks::Now() to get TimeTicks when 88 // used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks.
79 // scheduling tasks.
80 Timer(bool retain_user_task, bool is_repeating); 89 Timer(bool retain_user_task, bool is_repeating);
81 Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock); 90 Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock);
82 91
83 // Construct a timer with retained task info. If |tick_clock| is provided, it 92 // Construct a timer with retained task info. If |tick_clock| is provided, it
84 // is used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks. 93 // is used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks.
85 Timer(const tracked_objects::Location& posted_from, 94 Timer(const tracked_objects::Location& posted_from,
86 TimeDelta delay, 95 TimeDelta delay,
87 const base::Closure& user_task, 96 const base::Closure& user_task,
88 bool is_repeating); 97 bool is_repeating);
89 Timer(const tracked_objects::Location& posted_from, 98 Timer(const tracked_objects::Location& posted_from,
90 TimeDelta delay, 99 TimeDelta delay,
91 const base::Closure& user_task, 100 const base::Closure& user_task,
92 bool is_repeating, 101 bool is_repeating,
93 TickClock* tick_clock); 102 TickClock* tick_clock);
94 103
95 virtual ~Timer(); 104 virtual ~Timer();
96 105
97 // Returns true if the timer is running (i.e., not stopped). 106 // Returns true if the timer is running (i.e., not stopped).
98 virtual bool IsRunning() const; 107 virtual bool IsRunning() const;
99 108
100 // Returns the current delay for this timer. 109 // Returns the current delay for this timer.
101 virtual TimeDelta GetCurrentDelay() const; 110 virtual TimeDelta GetCurrentDelay() const;
102 111
103 // Set the task runner on which the task should be scheduled. This method can 112 // Set the task runner on which the task should be scheduled. This method can
104 // only be called before any tasks have been scheduled. The task runner must 113 // only be called before any tasks have been scheduled. If |task_runner| runs
105 // run tasks on the same thread the timer is used on. 114 // tasks on a different sequence than the sequence owning this Timer,
106 virtual void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner); 115 // |user_task_| will be posted to it when the Timer fires (note that this
116 // means |user_task_| can run after ~Timer() and should support that).
117 void SetTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner);
107 118
108 // Start the timer to run at the given |delay| from now. If the timer is 119 // Start the timer to run at the given |delay| from now. If the timer is
109 // already running, it will be replaced to call the given |user_task|. 120 // already running, it will be replaced to call the given |user_task|.
110 virtual void Start(const tracked_objects::Location& posted_from, 121 virtual void Start(const tracked_objects::Location& posted_from,
111 TimeDelta delay, 122 TimeDelta delay,
112 const base::Closure& user_task); 123 const base::Closure& user_task);
113 124
114 // Call this method to stop and cancel the timer. It is a no-op if the timer 125 // Call this method to stop and cancel the timer. It is a no-op if the timer
115 // is not running. 126 // is not running.
116 virtual void Stop(); 127 virtual void Stop();
117 128
118 // Call this method to reset the timer delay. The user_task_ must be set. If 129 // Call this method to reset the timer delay. The |user_task_| must be set. If
119 // the timer is not running, this will start it by posting a task. 130 // the timer is not running, this will start it by posting a task.
120 virtual void Reset(); 131 virtual void Reset();
121 132
122 const base::Closure& user_task() const { return user_task_; } 133 const base::Closure& user_task() const { return user_task_; }
123 const TimeTicks& desired_run_time() const { return desired_run_time_; } 134 const TimeTicks& desired_run_time() const { return desired_run_time_; }
124 135
125 protected: 136 protected:
126 // Returns the current tick count. 137 // Returns the current tick count.
127 TimeTicks Now() const; 138 TimeTicks Now() const;
128 139
129 // Used to initiate a new delayed task. This has the side-effect of disabling
130 // scheduled_task_ if it is non-null.
131 void SetTaskInfo(const tracked_objects::Location& posted_from,
132 TimeDelta delay,
133 const base::Closure& user_task);
134
135 void set_user_task(const Closure& task) { user_task_ = task; } 140 void set_user_task(const Closure& task) { user_task_ = task; }
136 void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; } 141 void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; }
137 void set_is_running(bool running) { is_running_ = running; } 142 void set_is_running(bool running) { is_running_ = running; }
138 143
139 const tracked_objects::Location& posted_from() const { return posted_from_; } 144 const tracked_objects::Location& posted_from() const { return posted_from_; }
140 bool retain_user_task() const { return retain_user_task_; } 145 bool retain_user_task() const { return retain_user_task_; }
141 bool is_repeating() const { return is_repeating_; } 146 bool is_repeating() const { return is_repeating_; }
142 bool is_running() const { return is_running_; } 147 bool is_running() const { return is_running_; }
143 148
144 private: 149 private:
145 friend class BaseTimerTaskInternal; 150 friend class BaseTimerTaskInternal;
146 151
147 // Allocates a new scheduled_task_ and posts it on the current MessageLoop 152 // Allocates a new |scheduled_task_| and posts it on the current sequence with
148 // with the given |delay|. scheduled_task_ must be NULL. scheduled_run_time_ 153 // the given |delay|. |scheduled_task_| must be null. |scheduled_run_time_|
149 // and desired_run_time_ are reset to Now() + delay. 154 // and |desired_run_time_| are reset to Now() + delay.
150 void PostNewScheduledTask(TimeDelta delay); 155 void PostNewScheduledTask(TimeDelta delay);
151 156
152 // Returns the task runner on which the task should be scheduled. If the 157 // Returns the task runner on which the task should be scheduled. If the
153 // corresponding task_runner_ field is null, the task runner for the current 158 // corresponding |task_runner_| field is null, the task runner for the current
154 // thread is returned. 159 // sequence is returned.
155 scoped_refptr<SingleThreadTaskRunner> GetTaskRunner(); 160 scoped_refptr<SequencedTaskRunner> GetTaskRunner();
156 161
157 // Disable scheduled_task_ and abandon it so that it no longer refers back to 162 // Disable |scheduled_task_| and abandon it so that it no longer refers back
158 // this object. 163 // to this object.
159 void AbandonScheduledTask(); 164 void AbandonScheduledTask();
160 165
161 // Called by BaseTimerTaskInternal when the MessageLoop runs it. 166 // Called by BaseTimerTaskInternal when the delayed task fires.
162 void RunScheduledTask(); 167 void RunScheduledTask();
163 168
164 // Stop running task (if any) and abandon scheduled task (if any). 169 // Stop running task (if any) and abandon scheduled task (if any).
165 void StopAndAbandon() { 170 void AbandonAndStop() {
166 AbandonScheduledTask(); 171 AbandonScheduledTask();
167 172
168 Stop(); 173 Stop();
169 // No more member accesses here: |this| could be deleted at this point. 174 // No more member accesses here: |this| could be deleted at this point.
170 } 175 }
171 176
172 // When non-NULL, the scheduled_task_ is waiting in the MessageLoop to call 177 // When non-null, the |scheduled_task_| was posted to call RunScheduledTask()
173 // RunScheduledTask() at scheduled_run_time_. 178 // at |scheduled_run_time_|.
174 BaseTimerTaskInternal* scheduled_task_; 179 BaseTimerTaskInternal* scheduled_task_;
175 180
176 // The task runner on which the task should be scheduled. If it is null, the 181 // The task runner on which the task should be scheduled. If it is null, the
177 // task runner for the current thread should be used. 182 // task runner for the current sequence will be used.
178 scoped_refptr<SingleThreadTaskRunner> task_runner_; 183 scoped_refptr<SequencedTaskRunner> task_runner_;
179 184
180 // Location in user code. 185 // Location in user code.
181 tracked_objects::Location posted_from_; 186 tracked_objects::Location posted_from_;
182 // Delay requested by user. 187 // Delay requested by user.
183 TimeDelta delay_; 188 TimeDelta delay_;
184 // user_task_ is what the user wants to be run at desired_run_time_. 189 // |user_task_| is what the user wants to be run at |desired_run_time_|.
185 base::Closure user_task_; 190 base::Closure user_task_;
186 191
187 // The estimated time that the MessageLoop will run the scheduled_task_ that 192 // The time at which |scheduled_task_| is expected to fire. This time can be a
188 // will call RunScheduledTask(). This time can be a "zero" TimeTicks if the 193 // "zero" TimeTicks if the task must be run immediately.
189 // task must be run immediately.
190 TimeTicks scheduled_run_time_; 194 TimeTicks scheduled_run_time_;
191 195
192 // The desired run time of user_task_. The user may update this at any time, 196 // The desired run time of |user_task_|. The user may update this at any time,
193 // even if their previous request has not run yet. If desired_run_time_ is 197 // even if their previous request has not run yet. If |desired_run_time_| is
194 // greater than scheduled_run_time_, a continuation task will be posted to 198 // greater than |scheduled_run_time_|, a continuation task will be posted to
195 // wait for the remaining time. This allows us to reuse the pending task so as 199 // wait for the remaining time. This allows us to reuse the pending task so as
196 // not to flood the MessageLoop with orphaned tasks when the user code 200 // not to flood the delayed queues with orphaned tasks when the user code
197 // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks 201 // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
198 // if the task must be run immediately. 202 // if the task must be run immediately.
199 TimeTicks desired_run_time_; 203 TimeTicks desired_run_time_;
200 204
201 // Thread ID of current MessageLoop for verifying single-threaded usage. 205 // Timer isn't thread-safe and must only be used on its origin sequence
202 int thread_id_; 206 // (sequence on which it was started).
207 SequenceChecker origin_sequence_checker_;
203 208
204 // Repeating timers automatically post the task again before calling the task 209 // Repeating timers automatically post the task again before calling the task
205 // callback. 210 // callback.
206 const bool is_repeating_; 211 const bool is_repeating_;
207 212
208 // If true, hold on to the user_task_ closure object for reuse. 213 // If true, hold on to the |user_task_| closure object for reuse.
209 const bool retain_user_task_; 214 const bool retain_user_task_;
210 215
211 // The tick clock used to calculate the run time for scheduled tasks. 216 // The tick clock used to calculate the run time for scheduled tasks.
212 TickClock* const tick_clock_; 217 TickClock* const tick_clock_;
213 218
214 // If true, user_task_ is scheduled to run sometime in the future. 219 // If true, |user_task_| is scheduled to run sometime in the future.
215 bool is_running_; 220 bool is_running_;
216 221
217 DISALLOW_COPY_AND_ASSIGN(Timer); 222 DISALLOW_COPY_AND_ASSIGN(Timer);
218 }; 223 };
219 224
220 //----------------------------------------------------------------------------- 225 //-----------------------------------------------------------------------------
221 // This class is an implementation detail of OneShotTimer and RepeatingTimer. 226 // This class is an implementation detail of OneShotTimer and RepeatingTimer.
222 // Please do not use this class directly. 227 // Please do not use this class directly.
223 class BaseTimerMethodPointer : public Timer { 228 class BaseTimerMethodPointer : public Timer {
224 public: 229 public:
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
259 // A simple, repeating timer. See usage notes at the top of the file. 264 // A simple, repeating timer. See usage notes at the top of the file.
260 class RepeatingTimer : public BaseTimerMethodPointer { 265 class RepeatingTimer : public BaseTimerMethodPointer {
261 public: 266 public:
262 RepeatingTimer() : RepeatingTimer(nullptr) {} 267 RepeatingTimer() : RepeatingTimer(nullptr) {}
263 explicit RepeatingTimer(TickClock* tick_clock) 268 explicit RepeatingTimer(TickClock* tick_clock)
264 : BaseTimerMethodPointer(REPEATING, tick_clock) {} 269 : BaseTimerMethodPointer(REPEATING, tick_clock) {}
265 }; 270 };
266 271
267 //----------------------------------------------------------------------------- 272 //-----------------------------------------------------------------------------
268 // A Delay timer is like The Button from Lost. Once started, you have to keep 273 // A Delay timer is like The Button from Lost. Once started, you have to keep
269 // calling Reset otherwise it will call the given method in the MessageLoop 274 // calling Reset otherwise it will call the given method on the sequence it was
270 // thread. 275 // initially Reset() from.
271 // 276 //
272 // Once created, it is inactive until Reset is called. Once |delay| seconds have 277 // Once created, it is inactive until Reset is called. Once |delay| seconds have
273 // passed since the last call to Reset, the callback is made. Once the callback 278 // passed since the last call to Reset, the callback is made. Once the callback
274 // has been made, it's inactive until Reset is called again. 279 // has been made, it's inactive until Reset is called again.
275 // 280 //
276 // If destroyed, the timeout is canceled and will not occur even if already 281 // If destroyed, the timeout is canceled and will not occur even if already
277 // inflight. 282 // inflight.
278 class DelayTimer : protected Timer { 283 class DelayTimer : protected Timer {
279 public: 284 public:
280 template <class Receiver> 285 template <class Receiver>
(...skipping 22 matching lines...) Expand all
303 // to link in MSVC. But clang-plugin does not allow inline definitions of 308 // to link in MSVC. But clang-plugin does not allow inline definitions of
304 // virtual methods, so the inline definition lives in the header file here 309 // virtual methods, so the inline definition lives in the header file here
305 // to satisfy both. 310 // to satisfy both.
306 inline void DelayTimer::Reset() { 311 inline void DelayTimer::Reset() {
307 Timer::Reset(); 312 Timer::Reset();
308 } 313 }
309 314
310 } // namespace base 315 } // namespace base
311 316
312 #endif // BASE_TIMER_TIMER_H_ 317 #endif // BASE_TIMER_TIMER_H_
OLDNEW
« no previous file with comments | « no previous file | base/timer/timer.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698