1 /* 2 * Copyright 2018 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 #pragma once 18 19 #include <base/bind.h> 20 #include <base/cancelable_callback.h> 21 #include <base/location.h> 22 #include <future> 23 24 namespace bluetooth { 25 26 namespace common { 27 28 class MessageLoopThread; 29 30 /** 31 * An alarm clock that posts a delayed task to a specified MessageLoopThread 32 * once. 33 * 34 * Warning: MessageLoopThread must be running when any task is scheduled or 35 * being executed 36 */ 37 class OnceTimer final { 38 public: OnceTimer()39 OnceTimer() {} 40 ~OnceTimer(); 41 42 /** 43 * Schedule a delayed task to the MessageLoopThread. Only one task can be 44 * scheduled at a time. If another task is scheduled, it will cancel the 45 * previous task synchronously and schedule the new task; this blocks until 46 * the previous task is cancelled. 47 * 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 delay delay for the task to be executed 52 * @return true iff task is scheduled successfully 53 */ 54 bool Schedule(const base::WeakPtr<MessageLoopThread>& thread, 55 const base::Location& from_here, base::OnceClosure task, 56 base::TimeDelta delay); 57 58 /** 59 * Post an event which cancels the current task asynchronously 60 */ 61 void Cancel(); 62 63 /** 64 * Post an event which cancels the current task and wait for the cancellation 65 * to be completed 66 */ 67 void CancelAndWait(); 68 69 /** 70 * Returns true when there is a pending task scheduled on a running thread, 71 * otherwise false. 72 */ 73 bool IsScheduled() const; 74 75 private: 76 base::WeakPtr<MessageLoopThread> message_loop_thread_; 77 base::CancelableOnceClosure task_wrapper_; 78 base::OnceClosure task_; 79 base::TimeDelta delay_; 80 mutable std::recursive_mutex api_mutex_; 81 void CancelHelper(std::promise<void> promise); 82 void CancelClosure(std::promise<void> promise); 83 84 void RunTask(); 85 86 DISALLOW_COPY_AND_ASSIGN(OnceTimer); 87 }; 88 89 } // namespace common 90 91 } // namespace bluetooth 92