2 * Copyright 2018 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <base/bind.h>
20 #include <base/cancelable_callback.h>
21 #include <base/location.h>
28 class MessageLoopThread;
31 * An alarm clock that posts a delayed task to a specified MessageLoopThread
34 * Warning: MessageLoopThread must be running when any task is scheduled or
37 class RepeatingTimer final {
39 RepeatingTimer() : expected_time_next_task_us_(0) {}
43 * Schedule a delayed periodic task to the MessageLoopThread. Only one task
44 * can be scheduled at a time. If another task is scheduled, it will cancel
45 * the previous task synchronously and schedule the new periodic task; this
46 * blocks until the previous task is cancelled.
48 * @param thread thread to run the task
49 * @param from_here location where this task is originated
50 * @param task task created through base::Bind()
51 * @param period period for the task to be executed
52 * @return true iff task is scheduled successfully
54 bool SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread,
55 const base::Location& from_here,
56 base::RepeatingClosure task, base::TimeDelta period);
59 * Post an event which cancels the current task asynchronously
64 * Post an event which cancels the current task and wait for the cancellation
70 * Returns true when there is a pending task scheduled on a running thread,
73 bool IsScheduled() const;
76 base::WeakPtr<MessageLoopThread> message_loop_thread_;
77 base::CancelableClosure task_wrapper_;
78 base::RepeatingClosure task_;
79 base::TimeDelta period_;
80 uint64_t expected_time_next_task_us_; // Using clock boot time in time_util.h
81 mutable std::recursive_mutex api_mutex_;
82 void CancelHelper(std::promise<void> promise);
83 void CancelClosure(std::promise<void> promise);
87 DISALLOW_COPY_AND_ASSIGN(RepeatingTimer);
92 } // namespace bluetooth