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 repeating 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.
34 class RepeatingAlarm {
35  public:
36   // Create and register a repeating alarm on a given handler
37   explicit RepeatingAlarm(Handler* handler);
38 
39   RepeatingAlarm(const RepeatingAlarm&) = delete;
40   RepeatingAlarm& operator=(const RepeatingAlarm&) = delete;
41 
42   // Unregister this alarm from the thread and release resource
43   ~RepeatingAlarm();
44 
45   // Schedule a repeating alarm with given period
46   void Schedule(common::Closure task, std::chrono::milliseconds period);
47 
48   // Cancel the alarm. No-op if it's not armed.
49   void Cancel();
50 
51  private:
52   common::Closure task_;
53   Handler* handler_;
54   int fd_ = 0;
55   Reactor::Reactable* token_;
56   mutable std::mutex mutex_;
57   void on_fire();
58 };
59 
60 }  // namespace os
61 }  // namespace bluetooth
62