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