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_",
45             task_.c_str());
46         return;
47     }
48 
49     auto task = [timeOutTask = shared_from_this()]() { timeOutTask->TimeOutProc(); };
50     handler_->PostTask(task, task_, delaytime);
51 }
TimeEnd()52 void AbilityPostEventTimeout::TimeEnd()
53 {
54     if (handler_ == nullptr) {
55         TAG_LOGE(AAFwkTag::ABILITY, "null %{public}s handler_", task_.c_str());
56         return;
57     }
58 
59     std::lock_guard<std::mutex> lck(mtx_);
60     if (!taskExec_) {
61         taskExec_ = true;
62         handler_->RemoveTask(task_);
63     }
64 }
65 
TimeOutProc()66 void AbilityPostEventTimeout::TimeOutProc()
67 {
68     TAG_LOGI(AAFwkTag::ABILITY, "call %{public}s", task_.c_str());
69     if (handler_ == nullptr) {
70         TAG_LOGE(AAFwkTag::ABILITY, "null %{public}s handler_", task_.c_str());
71         return;
72     }
73 
74     std::lock_guard<std::mutex> lck(mtx_);
75     if (!taskExec_) {
76         taskExec_ = true;
77         TAG_LOGW(AAFwkTag::ABILITY, "%{public}s TimeOut", task_.c_str());
78         handler_->RemoveTask(task_);
79     } else {
80         TAG_LOGW(AAFwkTag::ABILITY, "Failed,Event:%{public}s",
81             task_.c_str());
82     }
83 }
84 }  // namespace AppExecFwk
85 }  // namespace OHOS
86