1 /*
2 * Copyright (c) 2021 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_call_back.h"
17 #include "time_service_client.h"
18
19 namespace OHOS {
20 namespace MiscServices {
21 std::mutex TimerCallback::instanceLock_;
22 sptr<TimerCallback> TimerCallback::instance_;
23
TimerCallback()24 TimerCallback::TimerCallback()
25 {
26 }
27
~TimerCallback()28 TimerCallback::~TimerCallback()
29 {
30 }
31
GetInstance()32 sptr<TimerCallback> TimerCallback::GetInstance()
33 {
34 if (instance_ == nullptr) {
35 std::lock_guard<std::mutex> autoLock(instanceLock_);
36 if (instance_ == nullptr) {
37 instance_ = new TimerCallback;
38 }
39 }
40 return instance_;
41 }
42
InsertTimerCallbackInfo(uint64_t timerId,const std::shared_ptr<ITimerInfo> & timerInfo)43 bool TimerCallback::InsertTimerCallbackInfo(uint64_t timerId, const std::shared_ptr<ITimerInfo> &timerInfo)
44 {
45 TIME_HILOGD(TIME_MODULE_SERVICE, "start");
46 if (timerInfo == nullptr) {
47 return false;
48 }
49
50 std::lock_guard<std::mutex> lock(timerInfoMutex_);
51 auto info = timerInfoMap_.find(timerId);
52 if (info != timerInfoMap_.end()) {
53 TIME_HILOGE(TIME_MODULE_CLIENT, "timer info already insert");
54 return false;
55 } else {
56 timerInfoMap_[timerId] = timerInfo;
57 }
58 TIME_HILOGD(TIME_MODULE_SERVICE, "end");
59 return true;
60 }
61
RemoveTimerCallbackInfo(uint64_t timerId)62 bool TimerCallback::RemoveTimerCallbackInfo(uint64_t timerId)
63 {
64 TIME_HILOGD(TIME_MODULE_SERVICE, "start");
65 std::lock_guard<std::mutex> lock(timerInfoMutex_);
66 auto info = timerInfoMap_.find(timerId);
67 if (info != timerInfoMap_.end()) {
68 timerInfoMap_.erase(info);
69 TIME_HILOGD(TIME_MODULE_SERVICE, "end");
70 return true;
71 }
72 TIME_HILOGD(TIME_MODULE_SERVICE, "end");
73 return false;
74 }
75
NotifyTimer(const uint64_t timerId)76 int32_t TimerCallback::NotifyTimer(const uint64_t timerId)
77 {
78 TIME_HILOGD(TIME_MODULE_SERVICE, "start");
79 std::shared_ptr<ITimerInfo> timerInfo;
80 {
81 std::lock_guard<std::mutex> lock(timerInfoMutex_);
82 auto it = timerInfoMap_.find(timerId);
83 if (it != timerInfoMap_.end()) {
84 TIME_HILOGD(TIME_MODULE_SERVICE, "ontrigger");
85 timerInfo = it->second;
86 }
87 }
88 if (timerInfo != nullptr) {
89 timerInfo->OnTrigger();
90 }
91 TIME_HILOGD(TIME_MODULE_SERVICE, "end");
92 TimeServiceClient::GetInstance()->HandleRecoverMap(timerId);
93 return E_TIME_OK;
94 }
95 } // namespace MiscServices
96 } // namespace OHOS