1 /*
2 * Copyright (c) 2022 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 #include "conditions/timer_listener.h"
16
17 #include "work_queue_event_handler.h"
18 #include "work_sched_hilog.h"
19 #include "conditions/timer_info.h"
20
21 namespace OHOS {
22 namespace WorkScheduler {
TimerListener(std::shared_ptr<WorkQueueManager> workQueueManager,const std::shared_ptr<AppExecFwk::EventRunner> & runner)23 TimerListener::TimerListener(std::shared_ptr<WorkQueueManager> workQueueManager,
24 const std::shared_ptr<AppExecFwk::EventRunner>& runner)
25 {
26 workQueueManager_ = workQueueManager;
27 }
28
OnConditionChanged(WorkCondition::Type conditionType,std::shared_ptr<DetectorValue> conditionVal)29 void TimerListener::OnConditionChanged(WorkCondition::Type conditionType,
30 std::shared_ptr<DetectorValue> conditionVal)
31 {
32 workQueueManager_->OnConditionChanged(conditionType, conditionVal);
33 }
34
Start()35 bool TimerListener::Start()
36 {
37 if (workQueueManager_ == nullptr) {
38 WS_HILOGE("workQueueManager_ is null");
39 return false;
40 }
41 uint32_t time = workQueueManager_->GetTimeCycle();
42 WS_HILOGI("TimerListener start with time = %{public}u.", time);
43 auto task = [=]() {
44 WS_HILOGI("begin check repeat work");
45 workQueueManager_->OnConditionChanged(WorkCondition::Type::TIMER, std::make_shared<
46 DetectorValue>(0, 0, 0, std::string()));
47 };
48 auto timerInfo = std::make_shared<TimerInfo>();
49 uint8_t type = static_cast<uint8_t>(timerInfo->TIMER_TYPE_EXACT) |
50 static_cast<uint8_t>(timerInfo->TIMER_TYPE_REALTIME);
51 timerInfo->SetType(static_cast<int>(type));
52 timerInfo->SetRepeat(true);
53 timerInfo->SetInterval(time);
54 timerInfo->SetCallbackInfo(task);
55 timerId_ = TimeServiceClient::GetInstance()->CreateTimer(timerInfo);
56 if (timerId_ == 0) {
57 WS_HILOGE("TimerListener CreateTimer failed");
58 return false;
59 }
60 bool res = TimeServiceClient::GetInstance()->StartTimer(timerId_,
61 TimeServiceClient::GetInstance()->GetBootTimeMs() + time);
62 WS_HILOGI("res is %{public}d, timerId = %{public}" PRIu64, res, timerId_);
63 return true;
64 }
65
Stop()66 bool TimerListener::Stop()
67 {
68 if (timerId_ > 0) {
69 MiscServices::TimeServiceClient::GetInstance()->StopTimer(timerId_);
70 MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(timerId_);
71 timerId_ = 0;
72 }
73 return true;
74 }
75 } // namespace WorkScheduler
76 } // namespace OHOS