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 // OneShotTimer and RepeatingTimer provide a simple timer API. As the names
6 // suggest, OneShotTimer calls you back once after a time delay expires.
7 // RepeatingTimer on the other hand calls you back periodically with the
8 // prescribed time interval.
10 // OneShotTimer and RepeatingTimer both cancel the timer when they go out of
11 // scope, which makes it easy to ensure that you do not get called when your
12 // object has gone out of scope. Just instantiate a OneShotTimer or
13 // RepeatingTimer as a member variable of the class for which you wish to
14 // receive timer events.
16 // Sample RepeatingTimer usage:
20 // void StartDoingStuff() {
21 // timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1),
22 // this, &MyClass::DoStuff);
24 // void StopDoingStuff() {
29 // // This method is called every second to do stuff.
32 // base::RepeatingTimer<MyClass> timer_;
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
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
39 // other words, Reset is shorthand for calling Stop and then Start again with
40 // the same arguments.
42 // NOTE: These APIs are not thread safe. Always call from the same thread.
44 #ifndef BASE_TIMER_TIMER_H_
45 #define BASE_TIMER_TIMER_H_
47 // IMPORTANT: If you change timer code, make sure that all tests (including
48 // 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
50 // should be able to tell the difference.
52 #include "base/base_export.h"
53 #include "base/basictypes.h"
54 #include "base/bind.h"
55 #include "base/bind_helpers.h"
56 #include "base/callback.h"
57 #include "base/location.h"
58 #include "base/time/time.h"
62 class BaseTimerTaskInternal
;
63 class SingleThreadTaskRunner
;
65 //-----------------------------------------------------------------------------
66 // This class wraps MessageLoop::PostDelayedTask to manage delayed and repeating
67 // tasks. It must be destructed on the same thread that starts tasks. There are
68 // DCHECKs in place to verify this.
70 class BASE_EXPORT Timer
{
72 // Construct a timer in repeating or one-shot mode. Start or SetTaskInfo must
73 // be called later to set task info. |retain_user_task| determines whether the
74 // user_task is retained or reset when it runs or stops.
75 Timer(bool retain_user_task
, bool is_repeating
);
77 // Construct a timer with retained task info.
78 Timer(const tracked_objects::Location
& posted_from
,
80 const base::Closure
& user_task
,
85 // Returns true if the timer is running (i.e., not stopped).
86 virtual bool IsRunning() const;
88 // Returns the current delay for this timer.
89 virtual TimeDelta
GetCurrentDelay() const;
91 // Set the task runner on which the task should be scheduled. This method can
92 // only be called before any tasks have been scheduled. The task runner must
93 // run tasks on the same thread the timer is used on.
94 virtual void SetTaskRunner(scoped_refptr
<SingleThreadTaskRunner
> task_runner
);
96 // Start the timer to run at the given |delay| from now. If the timer is
97 // already running, it will be replaced to call the given |user_task|.
98 virtual void Start(const tracked_objects::Location
& posted_from
,
100 const base::Closure
& user_task
);
102 // Call this method to stop and cancel the timer. It is a no-op if the timer
106 // Call this method to reset the timer delay. The user_task_ must be set. If
107 // the timer is not running, this will start it by posting a task.
108 virtual void Reset();
110 const base::Closure
& user_task() const { return user_task_
; }
111 const TimeTicks
& desired_run_time() const { return desired_run_time_
; }
114 // Used to initiate a new delayed task. This has the side-effect of disabling
115 // scheduled_task_ if it is non-null.
116 void SetTaskInfo(const tracked_objects::Location
& posted_from
,
118 const base::Closure
& user_task
);
120 void set_user_task(const Closure
& task
) { user_task_
= task
; }
121 void set_desired_run_time(TimeTicks desired
) { desired_run_time_
= desired
; }
122 void set_is_running(bool running
) { is_running_
= running
; }
124 const tracked_objects::Location
& posted_from() const { return posted_from_
; }
125 bool retain_user_task() const { return retain_user_task_
; }
126 bool is_repeating() const { return is_repeating_
; }
127 bool is_running() const { return is_running_
; }
130 friend class BaseTimerTaskInternal
;
132 // Allocates a new scheduled_task_ and posts it on the current MessageLoop
133 // with the given |delay|. scheduled_task_ must be NULL. scheduled_run_time_
134 // and desired_run_time_ are reset to Now() + delay.
135 void PostNewScheduledTask(TimeDelta delay
);
137 // Returns the task runner on which the task should be scheduled. If the
138 // corresponding task_runner_ field is null, the task runner for the current
139 // thread is returned.
140 scoped_refptr
<SingleThreadTaskRunner
> GetTaskRunner();
142 // Disable scheduled_task_ and abandon it so that it no longer refers back to
144 void AbandonScheduledTask();
146 // Called by BaseTimerTaskInternal when the MessageLoop runs it.
147 void RunScheduledTask();
149 // Stop running task (if any) and abandon scheduled task (if any).
150 void StopAndAbandon() {
152 AbandonScheduledTask();
155 // When non-NULL, the scheduled_task_ is waiting in the MessageLoop to call
156 // RunScheduledTask() at scheduled_run_time_.
157 BaseTimerTaskInternal
* scheduled_task_
;
159 // The task runner on which the task should be scheduled. If it is null, the
160 // task runner for the current thread should be used.
161 scoped_refptr
<SingleThreadTaskRunner
> task_runner_
;
163 // Location in user code.
164 tracked_objects::Location posted_from_
;
165 // Delay requested by user.
167 // user_task_ is what the user wants to be run at desired_run_time_.
168 base::Closure user_task_
;
170 // The estimated time that the MessageLoop will run the scheduled_task_ that
171 // will call RunScheduledTask(). This time can be a "zero" TimeTicks if the
172 // task must be run immediately.
173 TimeTicks scheduled_run_time_
;
175 // The desired run time of user_task_. The user may update this at any time,
176 // even if their previous request has not run yet. If desired_run_time_ is
177 // greater than scheduled_run_time_, a continuation task will be posted to
178 // wait for the remaining time. This allows us to reuse the pending task so as
179 // not to flood the MessageLoop with orphaned tasks when the user code
180 // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
181 // if the task must be run immediately.
182 TimeTicks desired_run_time_
;
184 // Thread ID of current MessageLoop for verifying single-threaded usage.
187 // Repeating timers automatically post the task again before calling the task
189 const bool is_repeating_
;
191 // If true, hold on to the user_task_ closure object for reuse.
192 const bool retain_user_task_
;
194 // If true, user_task_ is scheduled to run sometime in the future.
197 DISALLOW_COPY_AND_ASSIGN(Timer
);
200 //-----------------------------------------------------------------------------
201 // This class is an implementation detail of OneShotTimer and RepeatingTimer.
202 // Please do not use this class directly.
203 template <class Receiver
, bool kIsRepeating
>
204 class BaseTimerMethodPointer
: public Timer
{
206 typedef void (Receiver::*ReceiverMethod
)();
208 // This is here to work around the fact that Timer::Start is "hidden" by the
209 // Start definition below, rather than being overloaded.
210 // TODO(tim): We should remove uses of BaseTimerMethodPointer::Start below
211 // and convert callers to use the base::Closure version in Timer::Start,
215 BaseTimerMethodPointer() : Timer(kIsRepeating
, kIsRepeating
) {}
217 // Start the timer to run at the given |delay| from now. If the timer is
218 // already running, it will be replaced to call a task formed from
219 // |reviewer->*method|.
220 virtual void Start(const tracked_objects::Location
& posted_from
,
223 ReceiverMethod method
) {
224 Timer::Start(posted_from
, delay
,
225 base::Bind(method
, base::Unretained(receiver
)));
229 //-----------------------------------------------------------------------------
230 // A simple, one-shot timer. See usage notes at the top of the file.
231 template <class Receiver
>
232 class OneShotTimer
: public BaseTimerMethodPointer
<Receiver
, false> {};
234 //-----------------------------------------------------------------------------
235 // A simple, repeating timer. See usage notes at the top of the file.
236 template <class Receiver
>
237 class RepeatingTimer
: public BaseTimerMethodPointer
<Receiver
, true> {};
239 //-----------------------------------------------------------------------------
240 // A Delay timer is like The Button from Lost. Once started, you have to keep
241 // calling Reset otherwise it will call the given method in the MessageLoop
244 // Once created, it is inactive until Reset is called. Once |delay| seconds have
245 // passed since the last call to Reset, the callback is made. Once the callback
246 // has been made, it's inactive until Reset is called again.
248 // If destroyed, the timeout is canceled and will not occur even if already
250 template <class Receiver
>
251 class DelayTimer
: protected Timer
{
253 typedef void (Receiver::*ReceiverMethod
)();
255 DelayTimer(const tracked_objects::Location
& posted_from
,
258 ReceiverMethod method
)
259 : Timer(posted_from
, delay
,
260 base::Bind(method
, base::Unretained(receiver
)),
263 void Reset() override
{ Timer::Reset(); }
268 #endif // BASE_TIMER_TIMER_H_