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

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

Issue 2491613004: Make base::Timer sequence-friendly. (Closed)
Patch Set: rebase Created 4 years 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
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 21 matching lines...) Expand all
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. Always call from the same sequenced task
43 // runner - thread or worker pool. By default the scheduled tasks will be run
44 // on the same sequence that the APIs are called from, but this can be changed
45 // prior to any tasks being scheduled using SetTaskRunner().
43 46
44 #ifndef BASE_TIMER_TIMER_H_ 47 #ifndef BASE_TIMER_TIMER_H_
45 #define BASE_TIMER_TIMER_H_ 48 #define BASE_TIMER_TIMER_H_
46 49
47 // IMPORTANT: If you change timer code, make sure that all tests (including 50 // IMPORTANT: If you change timer code, make sure that all tests (including
48 // disabled ones) from timer_unittests.cc pass locally. Some are disabled 51 // 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 52 // because they're flaky on the buildbot, but when you run them locally you
50 // should be able to tell the difference. 53 // should be able to tell the difference.
51 54
52 #include <memory> 55 #include <memory>
53 56
54 #include "base/base_export.h" 57 #include "base/base_export.h"
55 #include "base/bind.h" 58 #include "base/bind.h"
56 #include "base/bind_helpers.h" 59 #include "base/bind_helpers.h"
57 #include "base/callback.h" 60 #include "base/callback.h"
58 #include "base/location.h" 61 #include "base/location.h"
59 #include "base/macros.h" 62 #include "base/macros.h"
63 #include "base/memory/weak_ptr.h"
64 #include "base/sequence_checker.h"
60 #include "base/time/time.h" 65 #include "base/time/time.h"
61 66
62 namespace base { 67 namespace base {
63 68
64 class BaseTimerTaskInternal; 69 class BaseTimerTaskInternal;
65 class SingleThreadTaskRunner; 70 class SequencedTaskRunner;
66 class TickClock; 71 class TickClock;
67 72
68 //----------------------------------------------------------------------------- 73 //-----------------------------------------------------------------------------
69 // This class wraps MessageLoop::PostDelayedTask to manage delayed and repeating 74 // 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 75 // tasks. A Timer is bound to the sequence on which it is started. To destroy it
71 // DCHECKs in place to verify this. 76 // on its initial sequence (shall it differ) it must first be stopped on the
77 // sequence it's bound to. There are DCHECKs in place to verify this. Note:
78 // Timer is sequence-affine, but may become thread-affine if coupled with a
79 // thread-affine TickClock.
72 // 80 //
73 class BASE_EXPORT Timer { 81 class BASE_EXPORT Timer {
74 public: 82 public:
75 // Construct a timer in repeating or one-shot mode. Start or SetTaskInfo must 83 // Construct a timer in repeating or one-shot mode. Start must
76 // be called later to set task info. |retain_user_task| determines whether the 84 // be called later to set task info. |retain_user_task| determines whether the
77 // user_task is retained or reset when it runs or stops. If |tick_clock| is 85 // user_task is retained or reset when it runs or stops. If |tick_clock| is
78 // provided, it is used instead of TimeTicks::Now() to get TimeTicks when 86 // provided, it is used instead of TimeTicks::Now() to get TimeTicks when
79 // scheduling tasks. 87 // scheduling tasks.
80 Timer(bool retain_user_task, bool is_repeating); 88 Timer(bool retain_user_task, bool is_repeating);
81 Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock); 89 Timer(bool retain_user_task, bool is_repeating, TickClock* tick_clock);
82 90
83 // Construct a timer with retained task info. If |tick_clock| is provided, it 91 // 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. 92 // is used instead of TimeTicks::Now() to get TimeTicks when scheduling tasks.
85 Timer(const tracked_objects::Location& posted_from, 93 Timer(const tracked_objects::Location& posted_from,
86 TimeDelta delay, 94 TimeDelta delay,
87 const base::Closure& user_task, 95 const base::Closure& user_task,
88 bool is_repeating); 96 bool is_repeating);
89 Timer(const tracked_objects::Location& posted_from, 97 Timer(const tracked_objects::Location& posted_from,
90 TimeDelta delay, 98 TimeDelta delay,
91 const base::Closure& user_task, 99 const base::Closure& user_task,
92 bool is_repeating, 100 bool is_repeating,
93 TickClock* tick_clock); 101 TickClock* tick_clock);
94 102
95 virtual ~Timer(); 103 virtual ~Timer();
96 104
97 // Returns true if the timer is running (i.e., not stopped). 105 // Returns true if the timer is running (i.e., not stopped).
98 virtual bool IsRunning() const; 106 virtual bool IsRunning() const;
99 107
100 // Returns the current delay for this timer. 108 // Returns the current delay for this timer.
101 virtual TimeDelta GetCurrentDelay() const; 109 virtual TimeDelta GetCurrentDelay() const;
102 110
103 // Set the task runner on which the task should be scheduled. This method can 111 // 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 112 // only be called while this Timer is stopped. If a TickClock is set, it must
105 // run tasks on the same thread the timer is used on. 113 // support being used on both the "origin sequence" for this Timer and
106 virtual void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner); 114 // |task_runner|.
115 virtual void SetTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner);
107 116
108 // Start the timer to run at the given |delay| from now. If the timer is 117 // 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|. 118 // already running, it will be replaced to call the given |user_task|.
110 virtual void Start(const tracked_objects::Location& posted_from, 119 virtual void Start(const tracked_objects::Location& posted_from,
111 TimeDelta delay, 120 TimeDelta delay,
112 const base::Closure& user_task); 121 const base::Closure& user_task);
113 122
114 // Call this method to stop and cancel the timer. It is a no-op if the timer 123 // Call this method to stop and cancel the timer. It is a no-op if the timer
115 // is not running. 124 // is not running.
116 virtual void Stop(); 125 virtual void Stop();
117 126
118 // Call this method to reset the timer delay. The user_task_ must be set. If 127 // 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. 128 // the timer is not running, this will start it by posting a task.
120 virtual void Reset(); 129 virtual void Reset();
121 130
122 const base::Closure& user_task() const { return user_task_; } 131 const base::Closure& user_task() const { return user_task_; }
123 const TimeTicks& desired_run_time() const { return desired_run_time_; } 132 const TimeTicks& desired_run_time() const { return desired_run_time_; }
124 133
125 protected: 134 protected:
126 // Returns the current tick count. 135 // Returns the current tick count.
127 TimeTicks Now() const; 136 TimeTicks Now() const;
128 137
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; } 138 void set_user_task(const Closure& task) { user_task_ = task; }
136 void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; } 139 void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; }
137 void set_is_running(bool running) { is_running_ = running; } 140 void set_is_running(bool running) { is_running_ = running; }
138 141
139 const tracked_objects::Location& posted_from() const { return posted_from_; } 142 const tracked_objects::Location& posted_from() const { return posted_from_; }
140 bool retain_user_task() const { return retain_user_task_; } 143 bool retain_user_task() const { return retain_user_task_; }
141 bool is_repeating() const { return is_repeating_; } 144 bool is_repeating() const { return is_repeating_; }
142 bool is_running() const { return is_running_; } 145 bool is_running() const { return is_running_; }
143 146
144 private: 147 private:
145 friend class BaseTimerTaskInternal; 148 // Used to initiate a new delayed task. This has the side-effect of disabling
149 // scheduled_task_ if it is non-null.
150 void SetTaskInfo(const tracked_objects::Location& posted_from,
151 TimeDelta delay,
152 const base::Closure& user_task);
146 153
147 // Allocates a new scheduled_task_ and posts it on the current MessageLoop 154 // Allocates a new scheduled_task_ and posts it on the current MessageLoop
148 // with the given |delay|. scheduled_task_ must be NULL. scheduled_run_time_ 155 // with the given |delay|. This Timer must not be running when this is called.
149 // and desired_run_time_ are reset to Now() + delay.
150 void PostNewScheduledTask(TimeDelta delay); 156 void PostNewScheduledTask(TimeDelta delay);
151 157
152 // 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
154 // thread is returned.
155 scoped_refptr<SingleThreadTaskRunner> GetTaskRunner();
156
157 // Disable scheduled_task_ and abandon it so that it no longer refers back to 158 // Disable scheduled_task_ and abandon it so that it no longer refers back to
158 // this object. 159 // this object.
159 void AbandonScheduledTask(); 160 void AbandonScheduledTask();
160 161
161 // Called by BaseTimerTaskInternal when the MessageLoop runs it. 162 // Called by BaseTimerTaskInternal when the MessageLoop runs it.
162 void RunScheduledTask(); 163 void RunScheduledTask();
163 164
164 // Stop running task (if any) and abandon scheduled task (if any). 165 // This pointer must only be used to post Run()/Abandon() tasks through
165 void StopAndAbandon() { 166 // |scheduled_task_ref_->AsWeakPtr()| to the BaseTimerTaskInternal itself, it
166 Stop(); 167 // must not be dereferenced nor even used to check for null on the origin task
167 AbandonScheduledTask(); 168 // runner (|is_running_| is used instead to know whether there is a pending
168 } 169 // task). Note: for performance benefits it *can* be dereferenced inline iff
169 170 // GetTaskRunner()->RunsTasksOnCurrentThread().
170 // When non-NULL, the scheduled_task_ is waiting in the MessageLoop to call 171 WeakPtr<BaseTimerTaskInternal> scheduled_task_weak_ref_;
171 // RunScheduledTask() at scheduled_run_time_.
172 BaseTimerTaskInternal* scheduled_task_;
173 172
174 // The task runner on which the task should be scheduled. If it is null, the 173 // The task runner on which the task should be scheduled. If it is null, the
175 // task runner for the current thread should be used. 174 // task runner for the current sequence is used.
176 scoped_refptr<SingleThreadTaskRunner> task_runner_; 175 scoped_refptr<SequencedTaskRunner> destination_task_runner_;
177 176
178 // Location in user code. 177 // Location in user code.
179 tracked_objects::Location posted_from_; 178 tracked_objects::Location posted_from_;
180 // Delay requested by user. 179 // Delay requested by user.
181 TimeDelta delay_; 180 TimeDelta delay_;
182 // user_task_ is what the user wants to be run at desired_run_time_. 181 // user_task_ is what the user wants to be run at desired_run_time_.
183 base::Closure user_task_; 182 base::Closure user_task_;
184 183
185 // The estimated time that the MessageLoop will run the scheduled_task_ that 184 // The estimated time that the MessageLoop will run the scheduled_task_ that
186 // will call RunScheduledTask(). This time can be a "zero" TimeTicks if the 185 // will call RunScheduledTask(). This time can be a "zero" TimeTicks if the
187 // task must be run immediately. 186 // task must be run immediately.
188 TimeTicks scheduled_run_time_; 187 TimeTicks scheduled_run_time_;
189 188
190 // The desired run time of user_task_. The user may update this at any time, 189 // The desired run time of user_task_. The user may update this at any time,
191 // even if their previous request has not run yet. If desired_run_time_ is 190 // even if their previous request has not run yet. If desired_run_time_ is
192 // greater than scheduled_run_time_, a continuation task will be posted to 191 // greater than scheduled_run_time_, a continuation task will be posted to
193 // wait for the remaining time. This allows us to reuse the pending task so as 192 // wait for the remaining time. This allows us to reuse the pending task so as
194 // not to flood the MessageLoop with orphaned tasks when the user code 193 // not to flood the MessageLoop with orphaned tasks when the user code
195 // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks 194 // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
196 // if the task must be run immediately. 195 // if the task must be run immediately.
197 TimeTicks desired_run_time_; 196 TimeTicks desired_run_time_;
198 197
199 // Thread ID of current MessageLoop for verifying single-threaded usage. 198 // Calls to the timer are not thread safe, so a checker is used detect
200 int thread_id_; 199 // incorrect usage in debug builds. Uses SequenceCheckerImpl to allow usage in
200 // non-DCHECK logic in ~Timer(). Note that this only verifies interactions
201 // with this Timer's API; tasks themselves may be scheduled by on a different
202 // sequence if SetTaskRunner() is used.
203 SequenceCheckerImpl origin_sequence_checker_;
201 204
202 // Repeating timers automatically post the task again before calling the task 205 // Repeating timers automatically post the task again before calling the task
203 // callback. 206 // callback.
204 const bool is_repeating_; 207 const bool is_repeating_;
205 208
206 // If true, hold on to the user_task_ closure object for reuse. 209 // If true, hold on to the user_task_ closure object for reuse.
207 const bool retain_user_task_; 210 const bool retain_user_task_;
208 211
209 // The tick clock used to calculate the run time for scheduled tasks. 212 // The tick clock used to calculate the run time for scheduled tasks.
210 TickClock* const tick_clock_; 213 TickClock* const tick_clock_;
211 214
212 // If true, user_task_ is scheduled to run sometime in the future. 215 // If true, user_task_ is scheduled to run sometime in the future.
213 bool is_running_; 216 bool is_running_;
214 217
218 WeakPtrFactory<Timer> weak_ptr_factory_;
219
215 DISALLOW_COPY_AND_ASSIGN(Timer); 220 DISALLOW_COPY_AND_ASSIGN(Timer);
216 }; 221 };
217 222
218 //----------------------------------------------------------------------------- 223 //-----------------------------------------------------------------------------
219 // This class is an implementation detail of OneShotTimer and RepeatingTimer. 224 // This class is an implementation detail of OneShotTimer and RepeatingTimer.
220 // Please do not use this class directly. 225 // Please do not use this class directly.
221 class BaseTimerMethodPointer : public Timer { 226 class BaseTimerMethodPointer : public Timer {
222 public: 227 public:
223 // This is here to work around the fact that Timer::Start is "hidden" by the 228 // This is here to work around the fact that Timer::Start is "hidden" by the
224 // Start definition below, rather than being overloaded. 229 // Start definition below, rather than being overloaded.
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
257 // A simple, repeating timer. See usage notes at the top of the file. 262 // A simple, repeating timer. See usage notes at the top of the file.
258 class RepeatingTimer : public BaseTimerMethodPointer { 263 class RepeatingTimer : public BaseTimerMethodPointer {
259 public: 264 public:
260 RepeatingTimer() : RepeatingTimer(nullptr) {} 265 RepeatingTimer() : RepeatingTimer(nullptr) {}
261 explicit RepeatingTimer(TickClock* tick_clock) 266 explicit RepeatingTimer(TickClock* tick_clock)
262 : BaseTimerMethodPointer(REPEATING, tick_clock) {} 267 : BaseTimerMethodPointer(REPEATING, tick_clock) {}
263 }; 268 };
264 269
265 //----------------------------------------------------------------------------- 270 //-----------------------------------------------------------------------------
266 // A Delay timer is like The Button from Lost. Once started, you have to keep 271 // A Delay timer is like The Button from Lost. Once started, you have to keep
267 // calling Reset otherwise it will call the given method in the MessageLoop 272 // calling Reset otherwise it will call the given method on the task runner.
268 // thread.
269 // 273 //
270 // Once created, it is inactive until Reset is called. Once |delay| seconds have 274 // Once created, it is inactive until Reset is called. Once |delay| seconds have
271 // passed since the last call to Reset, the callback is made. Once the callback 275 // passed since the last call to Reset, the callback is made. Once the callback
272 // has been made, it's inactive until Reset is called again. 276 // has been made, it's inactive until Reset is called again.
273 // 277 //
274 // If destroyed, the timeout is canceled and will not occur even if already 278 // If destroyed, the timeout is canceled and will not occur even if already
275 // inflight. 279 // inflight.
276 class DelayTimer : protected Timer { 280 class DelayTimer : protected Timer {
277 public: 281 public:
278 template <class Receiver> 282 template <class Receiver>
(...skipping 22 matching lines...) Expand all
301 // to link in MSVC. But clang-plugin does not allow inline definitions of 305 // to link in MSVC. But clang-plugin does not allow inline definitions of
302 // virtual methods, so the inline definition lives in the header file here 306 // virtual methods, so the inline definition lives in the header file here
303 // to satisfy both. 307 // to satisfy both.
304 inline void DelayTimer::Reset() { 308 inline void DelayTimer::Reset() {
305 Timer::Reset(); 309 Timer::Reset();
306 } 310 }
307 311
308 } // namespace base 312 } // namespace base
309 313
310 #endif // BASE_TIMER_TIMER_H_ 314 #endif // BASE_TIMER_TIMER_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698