1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/timer/wall_clock_timer.h"
6
7 #include <utility>
8
9 #include "base/power_monitor/power_monitor.h"
10 #include "base/time/clock.h"
11 #include "base/time/default_clock.h"
12 #include "base/time/default_tick_clock.h"
13 #include "base/time/tick_clock.h"
14
15 namespace base {
16
17 WallClockTimer::WallClockTimer() = default;
WallClockTimer(const Clock * clock,const TickClock * tick_clock)18 WallClockTimer::WallClockTimer(const Clock* clock, const TickClock* tick_clock)
19 : timer_(tick_clock), clock_(clock ? clock : DefaultClock::GetInstance()) {}
20
~WallClockTimer()21 WallClockTimer::~WallClockTimer() {
22 RemoveObserver();
23 }
24
Start(const Location & posted_from,Time desired_run_time,OnceClosure user_task)25 void WallClockTimer::Start(const Location& posted_from,
26 Time desired_run_time,
27 OnceClosure user_task) {
28 user_task_ = std::move(user_task);
29 posted_from_ = posted_from;
30 desired_run_time_ = desired_run_time;
31 AddObserver();
32 timer_.Start(posted_from_, desired_run_time_ - Now(), this,
33 &WallClockTimer::RunUserTask);
34 }
35
Stop()36 void WallClockTimer::Stop() {
37 timer_.Stop();
38 user_task_.Reset();
39 RemoveObserver();
40 }
41
IsRunning() const42 bool WallClockTimer::IsRunning() const {
43 return timer_.IsRunning();
44 }
45
OnResume()46 void WallClockTimer::OnResume() {
47 // This will actually restart timer with smaller delay
48 timer_.Start(posted_from_, desired_run_time_ - Now(), this,
49 &WallClockTimer::RunUserTask);
50 }
51
AddObserver()52 void WallClockTimer::AddObserver() {
53 if (!observer_added_) {
54 PowerMonitor::AddPowerSuspendObserver(this);
55 observer_added_ = true;
56 }
57 }
58
RemoveObserver()59 void WallClockTimer::RemoveObserver() {
60 if (observer_added_) {
61 PowerMonitor::RemovePowerSuspendObserver(this);
62 observer_added_ = false;
63 }
64 }
65
RunUserTask()66 void WallClockTimer::RunUserTask() {
67 DCHECK(user_task_);
68 RemoveObserver();
69 std::exchange(user_task_, {}).Run();
70 }
71
Now() const72 Time WallClockTimer::Now() const {
73 return clock_->Now();
74 }
75
76 } // namespace base
77