1 /*
2  * Copyright (c) 2024 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 #include "timer_manager.h"
17 
18 #include <thread>
19 
20 #include "define_multimodal.h"
21 
22 namespace OHOS {
23 namespace MMI {
24 std::mutex TimerManager::mutex_;
25 std::shared_ptr<TimerManager> TimerManager::instance_;
26 
GetInstance()27 std::shared_ptr<TimerManager> TimerManager::GetInstance()
28 {
29     if (instance_ == nullptr) {
30         std::lock_guard<std::mutex> guard(mutex_);
31         if (instance_ == nullptr) {
32             instance_ = std::make_shared<TimerManager>();
33         }
34     }
35     return instance_;
36 }
37 
AddTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback)38 int32_t TimerManager::AddTimer(int32_t intervalMs, int32_t repeatCount, std::function<void()> callback)
39 {
40     if (running_.load()) {
41         return RET_ERR;
42     }
43     running_.store(true);
44     std::thread([=]() mutable {
45         do {
46             std::this_thread::sleep_for(std::chrono::milliseconds(intervalMs));
47             if (!running_.load()) {
48                 break;
49             }
50             if (callback != nullptr) {
51                 callback();
52             }
53         } while (running_.load() && (--repeatCount > 0));
54         running_.store(false);
55     }).detach();
56     return RET_OK;
57 }
58 
RemoveTimer(int32_t timerId)59 int32_t TimerManager::RemoveTimer(int32_t timerId)
60 {
61     running_.store(false);
62     return RET_OK;
63 }
64 
ResetTimer(int32_t timerId)65 int32_t TimerManager::ResetTimer(int32_t timerId)
66 {
67     return RET_OK;
68 }
69 } // namespace MMI
70 } // namespace OHOS
71