blob: e529fb9e4441cdcde2e373d3d6ac9172a4b17ccf [file] [log] [blame]
Hansong Zhanga25f84d2019-03-19 16:17:42 -07001/*
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
Hansong Zhangaa0875c2019-06-06 21:44:55 -070023#include "common/callback.h"
Myles Watson2ba4b302019-06-03 09:25:28 -070024#include "os/handler.h"
Hansong Zhanga25f84d2019-03-19 16:17:42 -070025#include "os/thread.h"
26#include "os/utils.h"
27
28namespace bluetooth {
29namespace 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, it will unregister
33// itself from the thread.
34class Alarm {
35 public:
Myles Watson2ba4b302019-06-03 09:25:28 -070036 // Create and register a single-shot alarm on a given handler
37 explicit Alarm(Handler* handler);
Hansong Zhanga25f84d2019-03-19 16:17:42 -070038
39 // Unregister this alarm from the thread and release resource
40 ~Alarm();
41
42 DISALLOW_COPY_AND_ASSIGN(Alarm);
43
44 // Schedule the alarm with given delay
Hansong Zhangaa0875c2019-06-06 21:44:55 -070045 void Schedule(OnceClosure task, std::chrono::milliseconds delay);
Hansong Zhanga25f84d2019-03-19 16:17:42 -070046
47 // Cancel the alarm. No-op if it's not armed.
48 void Cancel();
49
50 private:
Hansong Zhangaa0875c2019-06-06 21:44:55 -070051 OnceClosure task_;
Myles Watson2ba4b302019-06-03 09:25:28 -070052 Handler* handler_;
Hansong Zhanga25f84d2019-03-19 16:17:42 -070053 int fd_ = 0;
54 Reactor::Reactable* token_;
55 mutable std::mutex mutex_;
56 void on_fire();
57};
58
59} // namespace os
60
61} // namespace bluetooth