• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef TIMER_MANAGER_H
17 #define TIMER_MANAGER_H
18 
19 #include <future>
20 #include <functional>
21 #include <list>
22 #include <memory>
23 
24 #include "nocopyable.h"
25 
26 #include "i_context.h"
27 
28 namespace OHOS {
29 namespace Msdp {
30 namespace DeviceStatus {
31 class TimerManager final : public ITimerManager {
32 public:
33     TimerManager() = default;
34     DISALLOW_COPY_AND_MOVE(TimerManager);
35     ~TimerManager() = default;
36 
37     int32_t Init(IContext *context);
38     int32_t AddTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback) override;
39     int32_t RemoveTimer(int32_t timerId) override;
40     int32_t ResetTimer(int32_t timerId);
41     bool IsExist(int32_t timerId) const;
42     void ProcessTimers();
43     int32_t GetTimerFd() const;
44 
45 private:
46     struct TimerItem {
47         int32_t id { 0 };
48         int32_t intervalMs  { 0 };
49         int32_t repeatCount  { 0 };
50         int32_t callbackCount  { 0 };
51         int64_t nextCallTime  { 0 };
52         std::function<void()> callback { nullptr };
53     };
54 
55     int32_t OnInit(IContext *context);
56     int32_t OnAddTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback);
57     int32_t OnRemoveTimer(int32_t timerId);
58     int32_t OnResetTimer(int32_t timerId);
59     int32_t OnProcessTimers();
60     bool OnIsExist(int32_t timerId) const;
61     int32_t RunIsExist(std::packaged_task<bool(int32_t)> &task, int32_t timerId) const;
62     int32_t TakeNextTimerId();
63     int32_t AddTimerInternal(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback);
64     int32_t RemoveTimerInternal(int32_t timerId);
65     int32_t ResetTimerInternal(int32_t timerId);
66     void InsertTimerInternal(std::unique_ptr<TimerItem>& timer);
67     int64_t CalcNextDelayInternal();
68     void ProcessTimersInternal();
69     int32_t ArmTimer();
70 
71     int32_t timerFd_ { -1 };
72     IContext *context_ { nullptr };
73     std::list<std::unique_ptr<TimerItem>> timers_;
74 };
75 
GetTimerFd()76 inline int32_t TimerManager::GetTimerFd() const
77 {
78     return timerFd_;
79 }
80 } // namespace DeviceStatus
81 } // namespace Msdp
82 } // namespace OHOS
83 #endif // TIMER_MANAGER_H