1 /*
2 * Copyright (c) 2021-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 "ability_post_event_timeout.h"
17
18 #include "ability_handler.h"
19 #include "hilog_tag_wrapper.h"
20
21 namespace OHOS {
22 namespace AppExecFwk {
23 const int64_t AbilityPostEventTimeout::defalutDelayTime = 5000;
24
25 std::atomic<uint32_t> AbilityPostEventTimeout::allocationId_ = 0;
26
AbilityPostEventTimeout(std::string str,std::shared_ptr<AbilityHandler> & eventHandler)27 AbilityPostEventTimeout::AbilityPostEventTimeout(std::string str, std::shared_ptr<AbilityHandler> &eventHandler)
28 {
29 uint32_t taskId = allocationId_++;
30 std::string strId = std::to_string(taskId);
31 task_ = str + strId;
32 taskExec_ = false;
33 handler_ = eventHandler;
34 }
~AbilityPostEventTimeout()35 AbilityPostEventTimeout::~AbilityPostEventTimeout()
36 {
37 handler_.reset();
38 }
39
TimingBegin(int64_t delaytime)40 void AbilityPostEventTimeout::TimingBegin(int64_t delaytime)
41 {
42 TAG_LOGI(AAFwkTag::ABILITY, "call %{public}s", task_.c_str());
43 if (handler_ == nullptr) {
44 TAG_LOGE(AAFwkTag::ABILITY, "null %{public}s handler_", task_.c_str());
45 return;
46 }
47
48 auto task = [weak = weak_from_this()]() {
49 auto timeoutTask = weak.lock();
50 if (timeoutTask == nullptr) {
51 TAG_LOGE(AAFwkTag::APPKIT, "null timeout");
52 return;
53 }
54 timeoutTask->TimeOutProc();
55 };
56 handler_->PostTask(task, task_, delaytime);
57 }
TimeEnd()58 void AbilityPostEventTimeout::TimeEnd()
59 {
60 if (handler_ == nullptr) {
61 TAG_LOGE(AAFwkTag::ABILITY, "null %{public}s handler_", task_.c_str());
62 return;
63 }
64
65 std::lock_guard<std::mutex> lck(mtx_);
66 if (!taskExec_) {
67 taskExec_ = true;
68 handler_->RemoveTask(task_);
69 }
70 }
71
TimeOutProc()72 void AbilityPostEventTimeout::TimeOutProc()
73 {
74 TAG_LOGI(AAFwkTag::ABILITY, "call %{public}s", task_.c_str());
75 if (handler_ == nullptr) {
76 TAG_LOGE(AAFwkTag::ABILITY, "null handler_");
77 return;
78 }
79
80 std::lock_guard<std::mutex> lck(mtx_);
81 if (!taskExec_) {
82 taskExec_ = true;
83 TAG_LOGW(AAFwkTag::ABILITY, "%{public}s TimeOut", task_.c_str());
84 handler_->RemoveTask(task_);
85 } else {
86 TAG_LOGW(AAFwkTag::ABILITY, "failed,Event:%{public}s", task_.c_str());
87 }
88 }
89 } // namespace AppExecFwk
90 } // namespace OHOS
91