1 /* 2 * Copyright 2019 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 <functional> 20 #include <memory> 21 #include <mutex> 22 23 #include "common/callback.h" 24 #include "os/handler.h" 25 #include "os/thread.h" 26 #include "os/utils.h" 27 28 namespace bluetooth { 29 namespace os { 30 31 // A single-shot alarm for reactor-based thread, implemented by Linux timerfd. 32 // When it's constructed, it will register a reactable on the specified thread; when it's destroyed, 33 // it will unregister itself from the thread. 34 class Alarm { 35 public: 36 // Create and register a single-shot alarm on a given handler. This creates a wake alarm. 37 explicit Alarm(Handler* handler); 38 39 // Create and register a single-shot alarm on a given handler. 40 // This constructor can specify whether the alarm will be a wake alarm or a non-wake alarm. 41 explicit Alarm(Handler* handler, bool isWakeAlarm); 42 43 Alarm(const Alarm&) = delete; 44 Alarm& operator=(const Alarm&) = delete; 45 46 // Unregister this alarm from the thread and release resource 47 ~Alarm(); 48 49 // Schedule the alarm with given delay 50 void Schedule(common::OnceClosure task, std::chrono::milliseconds delay); 51 52 // Cancel the alarm. No-op if it's not armed. 53 void Cancel(); 54 55 private: 56 common::OnceClosure task_; 57 Handler* handler_; 58 int fd_ = 0; 59 Reactor::Reactable* token_; 60 mutable std::mutex mutex_; 61 void on_fire(); 62 }; 63 64 } // namespace os 65 66 } // namespace bluetooth 67