aboutsummaryrefslogtreecommitdiff
path: root/common/timer.cc
blob: f02a67dadc3b51639f26a2542b96c8fb2d1cc02d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "timer.h"
#include "message_loop_thread.h"
#include "time_util.h"

namespace bluetooth {

namespace common {

constexpr base::TimeDelta kMinimumPeriod = base::TimeDelta::FromMicroseconds(1);

// This runs on user thread
Timer::~Timer() {
  std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
  if (message_loop_thread_ != nullptr && message_loop_thread_->IsRunning()) {
    CancelAndWait();
  }
}

// This runs on user thread
bool Timer::Schedule(const base::WeakPtr<MessageLoopThread>& thread,
                     const tracked_objects::Location& from_here,
                     base::Closure task, base::TimeDelta delay) {
  return ScheduleTaskHelper(thread, from_here, std::move(task), delay, false);
}

// This runs on user thread
bool Timer::SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread,
                             const tracked_objects::Location& from_here,
                             base::Closure task, base::TimeDelta period) {
  if (period < kMinimumPeriod) {
    LOG(ERROR) << __func__ << ": period must be at least " << kMinimumPeriod;
    return false;
  }
  return ScheduleTaskHelper(thread, from_here, std::move(task), period, true);
}

// This runs on user thread
bool Timer::ScheduleTaskHelper(const base::WeakPtr<MessageLoopThread>& thread,
                               const tracked_objects::Location& from_here,
                               base::Closure task, base::TimeDelta delay,
                               bool is_periodic) {
  uint64_t time_now_us = time_get_os_boottime_us();
  uint64_t time_next_task_us = time_now_us + delay.InMicroseconds();
  std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
  if (thread == nullptr) {
    LOG(ERROR) << __func__ << ": thread must be non-null";
    return false;
  }
  CancelAndWait();
  expected_time_next_task_us_ = time_next_task_us;
  task_ = std::move(task);
  task_wrapper_.Reset(base::Bind(&Timer::RunTask, base::Unretained(this)));
  message_loop_thread_ = thread;
  period_ = delay;
  is_periodic_ = is_periodic;
  uint64_t time_until_next_us = time_next_task_us - time_get_os_boottime_us();
  if (!thread->DoInThreadDelayed(
          from_here, task_wrapper_.callback(),
          base::TimeDelta::FromMicroseconds(time_until_next_us))) {
    LOG(ERROR) << __func__
               << ": failed to post task to message loop for thread " << *thread
               << ", from " << from_here.ToString();
    expected_time_next_task_us_ = 0;
    task_wrapper_.Cancel();
    message_loop_thread_ = nullptr;
    period_ = {};
    is_periodic_ = false;
    return false;
  }
  return true;
}

// This runs on user thread
void Timer::Cancel() {
  std::promise<void> promise;
  CancelHelper(std::move(promise));
}

// This runs on user thread
void Timer::CancelAndWait() {
  std::promise<void> promise;
  auto future = promise.get_future();
  CancelHelper(std::move(promise));
  future.wait();
}

// This runs on user thread
void Timer::CancelHelper(std::promise<void> promise) {
  std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
  MessageLoopThread* scheduled_thread = message_loop_thread_.get();
  if (scheduled_thread == nullptr) {
    promise.set_value();
    return;
  }
  if (scheduled_thread->GetThreadId() == base::PlatformThread::CurrentId()) {
    CancelClosure(std::move(promise));
    return;
  }
  scheduled_thread->DoInThread(
      FROM_HERE, base::BindOnce(&Timer::CancelClosure, base::Unretained(this),
                                std::move(promise)));
}

// This runs on message loop thread
void Timer::CancelClosure(std::promise<void> promise) {
  message_loop_thread_ = nullptr;
  task_wrapper_.Cancel();
  task_ = {};
  period_ = base::TimeDelta();
  is_periodic_ = false;
  expected_time_next_task_us_ = 0;
  promise.set_value();
}

// This runs on user thread
bool Timer::IsScheduled() const {
  std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
  return message_loop_thread_ != nullptr && message_loop_thread_->IsRunning();
}

// This runs on message loop thread
void Timer::RunTask() {
  if (message_loop_thread_ == nullptr || !message_loop_thread_->IsRunning()) {
    LOG(ERROR) << __func__
               << ": message_loop_thread_ is null or is not running";
    return;
  }
  CHECK_EQ(message_loop_thread_->GetThreadId(),
           base::PlatformThread::CurrentId())
      << ": task must run on message loop thread";
  if (is_periodic_) {
    RunPeriodicTask();
  } else {
    RunSingleTask();
  }
}

// This runs on message loop thread
void Timer::RunPeriodicTask() {
  int64_t period_us = period_.InMicroseconds();
  expected_time_next_task_us_ += period_us;
  uint64_t time_now_us = time_get_os_boottime_us();
  int64_t remaining_time_us = expected_time_next_task_us_ - time_now_us;
  if (remaining_time_us < 0) {
    // if remaining_time_us is negative, schedule the task to the nearest
    // multiple of period
    remaining_time_us = (remaining_time_us % period_us + period_us) % period_us;
  }
  message_loop_thread_->DoInThreadDelayed(
      FROM_HERE, task_wrapper_.callback(),
      base::TimeDelta::FromMicroseconds(remaining_time_us));

  uint64_t time_before_task_us = time_get_os_boottime_us();
  task_.Run();
  uint64_t time_after_task_us = time_get_os_boottime_us();
  auto task_time_us =
      static_cast<int64_t>(time_after_task_us - time_before_task_us);
  if (task_time_us > period_.InMicroseconds()) {
    LOG(ERROR) << __func__ << ": Periodic task execution took " << task_time_us
               << " microseconds, longer than interval "
               << period_.InMicroseconds() << " microseconds";
  }
}

// This runs on message loop thread
void Timer::RunSingleTask() {
  base::OnceClosure current_task = std::move(task_);
  task_wrapper_.Cancel();
  task_ = {};
  period_ = base::TimeDelta();
  expected_time_next_task_us_ = 0;
  std::move(current_task).Run();
  message_loop_thread_ = nullptr;
}

}  // namespace common

}  // namespace bluetooth