Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / base / timer / timer.h
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.
4
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.
9 //
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.
15 //
16 // Sample RepeatingTimer usage:
17 //
18 //   class MyClass {
19 //    public:
20 //     void StartDoingStuff() {
21 //       timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1),
22 //                    this, &MyClass::DoStuff);
23 //     }
24 //     void StopDoingStuff() {
25 //       timer_.Stop();
26 //     }
27 //    private:
28 //     void DoStuff() {
29 //       // This method is called every second to do stuff.
30 //       ...
31 //     }
32 //     base::RepeatingTimer<MyClass> timer_;
33 //   };
34 //
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.
41 //
42 // NOTE: These APIs are not thread safe. Always call from the same thread.
43
44 #ifndef BASE_TIMER_TIMER_H_
45 #define BASE_TIMER_TIMER_H_
46
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.
51
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"
59
60 namespace base {
61
62 class BaseTimerTaskInternal;
63 class SingleThreadTaskRunner;
64
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.
69 //
70 class BASE_EXPORT Timer {
71  public:
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);
76
77   // Construct a timer with retained task info.
78   Timer(const tracked_objects::Location& posted_from,
79         TimeDelta delay,
80         const base::Closure& user_task,
81         bool is_repeating);
82
83   virtual ~Timer();
84
85   // Returns true if the timer is running (i.e., not stopped).
86   virtual bool IsRunning() const;
87
88   // Returns the current delay for this timer.
89   virtual TimeDelta GetCurrentDelay() const;
90
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.
93   virtual void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner);
94
95   // Start the timer to run at the given |delay| from now. If the timer is
96   // already running, it will be replaced to call the given |user_task|.
97   virtual void Start(const tracked_objects::Location& posted_from,
98                      TimeDelta delay,
99                      const base::Closure& user_task);
100
101   // Call this method to stop and cancel the timer.  It is a no-op if the timer
102   // is not running.
103   virtual void Stop();
104
105   // Call this method to reset the timer delay. The user_task_ must be set. If
106   // the timer is not running, this will start it by posting a task.
107   virtual void Reset();
108
109   const base::Closure& user_task() const { return user_task_; }
110   const TimeTicks& desired_run_time() const { return desired_run_time_; }
111
112  protected:
113   // Used to initiate a new delayed task.  This has the side-effect of disabling
114   // scheduled_task_ if it is non-null.
115   void SetTaskInfo(const tracked_objects::Location& posted_from,
116                    TimeDelta delay,
117                    const base::Closure& user_task);
118
119   void set_user_task(const Closure& task) { user_task_ = task; }
120   void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; }
121   void set_is_running(bool running) { is_running_ = running; }
122
123   const tracked_objects::Location& posted_from() const { return posted_from_; }
124   bool retain_user_task() const { return retain_user_task_; }
125   bool is_repeating() const { return is_repeating_; }
126   bool is_running() const { return is_running_; }
127
128  private:
129   friend class BaseTimerTaskInternal;
130
131   // Allocates a new scheduled_task_ and posts it on the current MessageLoop
132   // with the given |delay|. scheduled_task_ must be NULL. scheduled_run_time_
133   // and desired_run_time_ are reset to Now() + delay.
134   void PostNewScheduledTask(TimeDelta delay);
135
136   // Returns the task runner on which the task should be scheduled. If the
137   // corresponding task_runner_ field is null, the task runner for the current
138   // thread is returned.
139   scoped_refptr<SingleThreadTaskRunner> GetTaskRunner();
140
141   // Disable scheduled_task_ and abandon it so that it no longer refers back to
142   // this object.
143   void AbandonScheduledTask();
144
145   // Called by BaseTimerTaskInternal when the MessageLoop runs it.
146   void RunScheduledTask();
147
148   // Stop running task (if any) and abandon scheduled task (if any).
149   void StopAndAbandon() {
150     Stop();
151     AbandonScheduledTask();
152   }
153
154   // When non-NULL, the scheduled_task_ is waiting in the MessageLoop to call
155   // RunScheduledTask() at scheduled_run_time_.
156   BaseTimerTaskInternal* scheduled_task_;
157
158   // The task runner on which the task should be scheduled. If it is null, the
159   // task runner for the current thread should be used.
160   scoped_refptr<SingleThreadTaskRunner> task_runner_;
161
162   // Location in user code.
163   tracked_objects::Location posted_from_;
164   // Delay requested by user.
165   TimeDelta delay_;
166   // user_task_ is what the user wants to be run at desired_run_time_.
167   base::Closure user_task_;
168
169   // The estimated time that the MessageLoop will run the scheduled_task_ that
170   // will call RunScheduledTask(). This time can be a "zero" TimeTicks if the
171   // task must be run immediately.
172   TimeTicks scheduled_run_time_;
173
174   // The desired run time of user_task_. The user may update this at any time,
175   // even if their previous request has not run yet. If desired_run_time_ is
176   // greater than scheduled_run_time_, a continuation task will be posted to
177   // wait for the remaining time. This allows us to reuse the pending task so as
178   // not to flood the MessageLoop with orphaned tasks when the user code
179   // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
180   // if the task must be run immediately.
181   TimeTicks desired_run_time_;
182
183   // Thread ID of current MessageLoop for verifying single-threaded usage.
184   int thread_id_;
185
186   // Repeating timers automatically post the task again before calling the task
187   // callback.
188   const bool is_repeating_;
189
190   // If true, hold on to the user_task_ closure object for reuse.
191   const bool retain_user_task_;
192
193   // If true, user_task_ is scheduled to run sometime in the future.
194   bool is_running_;
195
196   DISALLOW_COPY_AND_ASSIGN(Timer);
197 };
198
199 //-----------------------------------------------------------------------------
200 // This class is an implementation detail of OneShotTimer and RepeatingTimer.
201 // Please do not use this class directly.
202 template <class Receiver, bool kIsRepeating>
203 class BaseTimerMethodPointer : public Timer {
204  public:
205   typedef void (Receiver::*ReceiverMethod)();
206
207   // This is here to work around the fact that Timer::Start is "hidden" by the
208   // Start definition below, rather than being overloaded.
209   // TODO(tim): We should remove uses of BaseTimerMethodPointer::Start below
210   // and convert callers to use the base::Closure version in Timer::Start,
211   // see bug 148832.
212   using Timer::Start;
213
214   BaseTimerMethodPointer() : Timer(kIsRepeating, kIsRepeating) {}
215
216   // Start the timer to run at the given |delay| from now. If the timer is
217   // already running, it will be replaced to call a task formed from
218   // |reviewer->*method|.
219   virtual void Start(const tracked_objects::Location& posted_from,
220                      TimeDelta delay,
221                      Receiver* receiver,
222                      ReceiverMethod method) {
223     Timer::Start(posted_from, delay,
224                  base::Bind(method, base::Unretained(receiver)));
225   }
226 };
227
228 //-----------------------------------------------------------------------------
229 // A simple, one-shot timer.  See usage notes at the top of the file.
230 template <class Receiver>
231 class OneShotTimer : public BaseTimerMethodPointer<Receiver, false> {};
232
233 //-----------------------------------------------------------------------------
234 // A simple, repeating timer.  See usage notes at the top of the file.
235 template <class Receiver>
236 class RepeatingTimer : public BaseTimerMethodPointer<Receiver, true> {};
237
238 //-----------------------------------------------------------------------------
239 // A Delay timer is like The Button from Lost. Once started, you have to keep
240 // calling Reset otherwise it will call the given method in the MessageLoop
241 // thread.
242 //
243 // Once created, it is inactive until Reset is called. Once |delay| seconds have
244 // passed since the last call to Reset, the callback is made. Once the callback
245 // has been made, it's inactive until Reset is called again.
246 //
247 // If destroyed, the timeout is canceled and will not occur even if already
248 // inflight.
249 template <class Receiver>
250 class DelayTimer : protected Timer {
251  public:
252   typedef void (Receiver::*ReceiverMethod)();
253
254   DelayTimer(const tracked_objects::Location& posted_from,
255              TimeDelta delay,
256              Receiver* receiver,
257              ReceiverMethod method)
258       : Timer(posted_from, delay,
259               base::Bind(method, base::Unretained(receiver)),
260               false) {}
261
262   void Reset() { Timer::Reset(); }
263 };
264
265 }  // namespace base
266
267 #endif  // BASE_TIMER_TIMER_H_