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