timer.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. // OneShotTimer, RepeatingTimer and RetainingOneShotTimer provide a simple timer
  5. // API. As the names suggest, OneShotTimer calls you back once after a time
  6. // delay expires.
  7. // RepeatingTimer on the other hand calls you back periodically with the
  8. // prescribed time interval.
  9. // RetainingOneShotTimer doesn't repeat the task itself like RepeatingTimer, but
  10. // retains the given task after the time out. You can restart it with Reset
  11. // again without giving new task to Start.
  12. //
  13. // All of OneShotTimer, RepeatingTimer and RetainingOneShotTimer cancel the
  14. // timer when they go out of scope, which makes it easy to ensure that you do
  15. // not get called when your object has gone out of scope. Just instantiate a
  16. // timer as a member variable of the class for which you wish to receive timer
  17. // events.
  18. //
  19. // Sample RepeatingTimer usage:
  20. //
  21. // class MyClass {
  22. // public:
  23. // void StartDoingStuff() {
  24. // timer_.Start(FROM_HERE, TimeDelta::FromSeconds(1),
  25. // this, &MyClass::DoStuff);
  26. // }
  27. // void StopDoingStuff() {
  28. // timer_.Stop();
  29. // }
  30. // private:
  31. // void DoStuff() {
  32. // // This method is called every second to do stuff.
  33. // ...
  34. // }
  35. // base::RepeatingTimer timer_;
  36. // };
  37. //
  38. // Timers also support a Reset method, which allows you to easily defer the
  39. // timer event until the timer delay passes once again. So, in the above
  40. // example, if 0.5 seconds have already passed, calling Reset on |timer_|
  41. // would postpone DoStuff by another 1 second. In other words, Reset is
  42. // shorthand for calling Stop and then Start again with the same arguments.
  43. //
  44. // These APIs are not thread safe. When a method is called (except the
  45. // constructor), all further method calls must be on the same sequence until
  46. // Stop().
  47. //
  48. // By default, the scheduled tasks will be run on the same sequence that the
  49. // Timer was *started on*. To mock time in unit tests, some old tests used
  50. // SetTaskRunner() to schedule the delay on a test-controlled TaskRunner. The
  51. // modern and preferred approach to mock time is to use TaskEnvironment's
  52. // MOCK_TIME mode.
  53. #ifndef BASE_TIMER_TIMER_H_
  54. #define BASE_TIMER_TIMER_H_
  55. // IMPORTANT: If you change timer code, make sure that all tests (including
  56. // disabled ones) from timer_unittests.cc pass locally. Some are disabled
  57. // because they're flaky on the buildbot, but when you run them locally you
  58. // should be able to tell the difference.
  59. #include <memory>
  60. #include "base/base_export.h"
  61. #include "base/bind.h"
  62. #include "base/bind_helpers.h"
  63. #include "base/callback.h"
  64. #include "base/location.h"
  65. #include "base/macros.h"
  66. #include "base/sequence_checker_impl.h"
  67. #include "base/sequenced_task_runner.h"
  68. #include "base/time/time.h"
  69. namespace base {
  70. class TickClock;
  71. namespace internal {
  72. class BaseTimerTaskInternal;
  73. //-----------------------------------------------------------------------------
  74. // This class wraps TaskRunner::PostDelayedTask to manage delayed and repeating
  75. // tasks. See meta comment above for thread-safety requirements.
  76. // Do not use this class directly. Use one of OneShotTimer, RepeatingTimer or
  77. // RetainingOneShotTimer.
  78. //
  79. class BASE_EXPORT TimerBase {
  80. public:
  81. // Constructs a timer. Start must be called later to set task info.
  82. // If |tick_clock| is provided, it is used instead of TimeTicks::Now() to get
  83. // TimeTicks when scheduling tasks.
  84. TimerBase();
  85. explicit TimerBase(const TickClock* tick_clock);
  86. // Construct a timer with task info.
  87. // If |tick_clock| is provided, it is used instead of TimeTicks::Now() to get
  88. // TimeTicks when scheduling tasks.
  89. TimerBase(const Location& posted_from, TimeDelta delay);
  90. TimerBase(const Location& posted_from,
  91. TimeDelta delay,
  92. const TickClock* tick_clock);
  93. virtual ~TimerBase();
  94. // Returns true if the timer is running (i.e., not stopped).
  95. bool IsRunning() const;
  96. // Returns the current delay for this timer.
  97. TimeDelta GetCurrentDelay() const;
  98. // Sets the task runner on which the delayed task should be scheduled when
  99. // this Timer is running. This method can only be called while this Timer
  100. // isn't running. This is an alternative (old) approach to mock time in tests.
  101. // The modern and preferred approach is to use
  102. // TaskEnvironment::TimeSource::MOCK_TIME. To avoid racy usage of Timer,
  103. // |task_runner| must run tasks on the same sequence which this Timer is bound
  104. // to (started from). TODO(gab): Migrate all callers to
  105. // TaskEnvironment::TimeSource::MOCK_TIME.
  106. virtual void SetTaskRunner(scoped_refptr<SequencedTaskRunner> task_runner);
  107. // Call this method to stop and cancel the timer. It is a no-op if the timer
  108. // is not running.
  109. virtual void Stop();
  110. // Stop running task (if any) and abandon scheduled task (if any).
  111. void AbandonAndStop() {
  112. AbandonScheduledTask();
  113. Stop();
  114. // No more member accesses here: |this| could be deleted at this point.
  115. }
  116. // Call this method to reset the timer delay. The user task must be set. If
  117. // the timer is not running, this will start it by posting a task.
  118. virtual void Reset();
  119. const TimeTicks& desired_run_time() const { return desired_run_time_; }
  120. protected:
  121. virtual void OnStop() = 0;
  122. virtual void RunUserTask() = 0;
  123. // Returns the current tick count.
  124. TimeTicks Now() const;
  125. void set_desired_run_time(TimeTicks desired) { desired_run_time_ = desired; }
  126. void set_is_running(bool running) { is_running_ = running; }
  127. const Location& posted_from() const { return posted_from_; }
  128. // The task runner on which the task should be scheduled. If it is null, the
  129. // task runner for the current sequence will be used.
  130. scoped_refptr<SequencedTaskRunner> task_runner_;
  131. // Timer isn't thread-safe and must only be used on its origin sequence
  132. // (sequence on which it was started). Once fully Stop()'ed it may be
  133. // destroyed or restarted on another sequence.
  134. SequenceChecker origin_sequence_checker_;
  135. // Allocates a new |scheduled_task_| and posts it on the current sequence with
  136. // the given |delay|. |scheduled_task_| must be null. |scheduled_run_time_|
  137. // and |desired_run_time_| are reset to Now() + delay.
  138. void PostNewScheduledTask(TimeDelta delay);
  139. void StartInternal(const Location& posted_from, TimeDelta delay);
  140. private:
  141. friend class BaseTimerTaskInternal;
  142. // Returns the task runner on which the task should be scheduled. If the
  143. // corresponding |task_runner_| field is null, the task runner for the current
  144. // sequence is returned.
  145. scoped_refptr<SequencedTaskRunner> GetTaskRunner();
  146. // Disable |scheduled_task_| and abandon it so that it no longer refers back
  147. // to this object.
  148. void AbandonScheduledTask();
  149. // Called by BaseTimerTaskInternal when the delayed task fires.
  150. void RunScheduledTask();
  151. // When non-null, the |scheduled_task_| was posted to call RunScheduledTask()
  152. // at |scheduled_run_time_|.
  153. BaseTimerTaskInternal* scheduled_task_;
  154. // Location in user code.
  155. Location posted_from_;
  156. // Delay requested by user.
  157. TimeDelta delay_;
  158. // The time at which |scheduled_task_| is expected to fire. This time can be a
  159. // "zero" TimeTicks if the task must be run immediately.
  160. TimeTicks scheduled_run_time_;
  161. // The desired run time of |user_task_|. The user may update this at any time,
  162. // even if their previous request has not run yet. If |desired_run_time_| is
  163. // greater than |scheduled_run_time_|, a continuation task will be posted to
  164. // wait for the remaining time. This allows us to reuse the pending task so as
  165. // not to flood the delayed queues with orphaned tasks when the user code
  166. // excessively Stops and Starts the timer. This time can be a "zero" TimeTicks
  167. // if the task must be run immediately.
  168. TimeTicks desired_run_time_;
  169. // The tick clock used to calculate the run time for scheduled tasks.
  170. const TickClock* const tick_clock_;
  171. // If true, |user_task_| is scheduled to run sometime in the future.
  172. bool is_running_;
  173. DISALLOW_COPY_AND_ASSIGN(TimerBase);
  174. };
  175. } // namespace internal
  176. //-----------------------------------------------------------------------------
  177. // A simple, one-shot timer. See usage notes at the top of the file.
  178. class BASE_EXPORT OneShotTimer : public internal::TimerBase {
  179. public:
  180. OneShotTimer();
  181. explicit OneShotTimer(const TickClock* tick_clock);
  182. ~OneShotTimer() override;
  183. // Start the timer to run at the given |delay| from now. If the timer is
  184. // already running, it will be replaced to call the given |user_task|.
  185. virtual void Start(const Location& posted_from,
  186. TimeDelta delay,
  187. OnceClosure user_task);
  188. // Start the timer to run at the given |delay| from now. If the timer is
  189. // already running, it will be replaced to call a task formed from
  190. // |receiver->*method|.
  191. template <class Receiver>
  192. void Start(const Location& posted_from,
  193. TimeDelta delay,
  194. Receiver* receiver,
  195. void (Receiver::*method)()) {
  196. Start(posted_from, delay, BindOnce(method, Unretained(receiver)));
  197. }
  198. // Run the scheduled task immediately, and stop the timer. The timer needs to
  199. // be running.
  200. void FireNow();
  201. private:
  202. void OnStop() final;
  203. void RunUserTask() final;
  204. OnceClosure user_task_;
  205. DISALLOW_COPY_AND_ASSIGN(OneShotTimer);
  206. };
  207. //-----------------------------------------------------------------------------
  208. // A simple, repeating timer. See usage notes at the top of the file.
  209. class BASE_EXPORT RepeatingTimer : public internal::TimerBase {
  210. public:
  211. RepeatingTimer();
  212. explicit RepeatingTimer(const TickClock* tick_clock);
  213. ~RepeatingTimer() override;
  214. RepeatingTimer(const Location& posted_from,
  215. TimeDelta delay,
  216. RepeatingClosure user_task);
  217. RepeatingTimer(const Location& posted_from,
  218. TimeDelta delay,
  219. RepeatingClosure user_task,
  220. const TickClock* tick_clock);
  221. // Start the timer to run at the given |delay| from now. If the timer is
  222. // already running, it will be replaced to call the given |user_task|.
  223. virtual void Start(const Location& posted_from,
  224. TimeDelta delay,
  225. RepeatingClosure user_task);
  226. // Start the timer to run at the given |delay| from now. If the timer is
  227. // already running, it will be replaced to call a task formed from
  228. // |receiver->*method|.
  229. template <class Receiver>
  230. void Start(const Location& posted_from,
  231. TimeDelta delay,
  232. Receiver* receiver,
  233. void (Receiver::*method)()) {
  234. Start(posted_from, delay, BindRepeating(method, Unretained(receiver)));
  235. }
  236. const RepeatingClosure& user_task() const { return user_task_; }
  237. private:
  238. // Mark this final, so that the destructor can call this safely.
  239. void OnStop() final;
  240. void RunUserTask() override;
  241. RepeatingClosure user_task_;
  242. DISALLOW_COPY_AND_ASSIGN(RepeatingTimer);
  243. };
  244. //-----------------------------------------------------------------------------
  245. // A simple, one-shot timer with the retained user_task which is reused for
  246. // multiple invocations of Start(). See usage notes at the top of the file.
  247. class BASE_EXPORT RetainingOneShotTimer : public internal::TimerBase {
  248. public:
  249. RetainingOneShotTimer();
  250. explicit RetainingOneShotTimer(const TickClock* tick_clock);
  251. ~RetainingOneShotTimer() override;
  252. RetainingOneShotTimer(const Location& posted_from,
  253. TimeDelta delay,
  254. RepeatingClosure user_task);
  255. RetainingOneShotTimer(const Location& posted_from,
  256. TimeDelta delay,
  257. RepeatingClosure user_task,
  258. const TickClock* tick_clock);
  259. // Start the timer to run at the given |delay| from now. If the timer is
  260. // already running, it will be replaced to call the given |user_task|.
  261. virtual void Start(const Location& posted_from,
  262. TimeDelta delay,
  263. RepeatingClosure user_task);
  264. // Start the timer to run at the given |delay| from now. If the timer is
  265. // already running, it will be replaced to call a task formed from
  266. // |receiver->*method|.
  267. template <class Receiver>
  268. void Start(const Location& posted_from,
  269. TimeDelta delay,
  270. Receiver* receiver,
  271. void (Receiver::*method)()) {
  272. Start(posted_from, delay, BindRepeating(method, Unretained(receiver)));
  273. }
  274. const RepeatingClosure& user_task() const { return user_task_; }
  275. protected:
  276. void set_user_task(const RepeatingClosure& task) { user_task_ = task; }
  277. private:
  278. // Mark this final, so that the destructor can call this safely.
  279. void OnStop() final;
  280. void RunUserTask() override;
  281. RepeatingClosure user_task_;
  282. DISALLOW_COPY_AND_ASSIGN(RetainingOneShotTimer);
  283. };
  284. //-----------------------------------------------------------------------------
  285. // A Delay timer is like The Button from Lost. Once started, you have to keep
  286. // calling Reset otherwise it will call the given method on the sequence it was
  287. // initially Reset() from.
  288. //
  289. // Once created, it is inactive until Reset is called. Once |delay| seconds have
  290. // passed since the last call to Reset, the callback is made. Once the callback
  291. // has been made, it's inactive until Reset is called again.
  292. //
  293. // If destroyed, the timeout is canceled and will not occur even if already
  294. // inflight.
  295. class DelayTimer {
  296. public:
  297. template <class Receiver>
  298. DelayTimer(const Location& posted_from,
  299. TimeDelta delay,
  300. Receiver* receiver,
  301. void (Receiver::*method)())
  302. : DelayTimer(posted_from, delay, receiver, method, nullptr) {}
  303. template <class Receiver>
  304. DelayTimer(const Location& posted_from,
  305. TimeDelta delay,
  306. Receiver* receiver,
  307. void (Receiver::*method)(),
  308. const TickClock* tick_clock)
  309. : timer_(posted_from,
  310. delay,
  311. BindRepeating(method, Unretained(receiver)),
  312. tick_clock) {}
  313. void Reset() { timer_.Reset(); }
  314. private:
  315. RetainingOneShotTimer timer_;
  316. DISALLOW_COPY_AND_ASSIGN(DelayTimer);
  317. };
  318. } // namespace base
  319. #endif // BASE_TIMER_TIMER_H_