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 "task_handler_client.h"
17 #include "hilog_tag_wrapper.h"
18 
19 namespace OHOS {
20 namespace AppExecFwk {
21 std::shared_ptr<TaskHandlerClient> TaskHandlerClient::instance_ = nullptr;
22 std::mutex TaskHandlerClient::mutex_;
23 
GetInstance()24 std::shared_ptr<TaskHandlerClient> TaskHandlerClient::GetInstance()
25 {
26     if (instance_ == nullptr) {
27         std::lock_guard<std::mutex> lock_l(mutex_);
28         if (instance_ == nullptr) {
29             instance_ = std::make_shared<TaskHandlerClient>();
30         }
31     }
32     return instance_;
33 }
34 
TaskHandlerClient()35 TaskHandlerClient::TaskHandlerClient()
36 {}
37 
~TaskHandlerClient()38 TaskHandlerClient::~TaskHandlerClient()
39 {}
40 
PostTask(std::function<void ()> task,long delayTime)41 bool TaskHandlerClient::PostTask(std::function<void()> task, long delayTime)
42 {
43     TAG_LOGI(AAFwkTag::ABILITY, "called");
44 
45     if (taskHandler_ == nullptr) {
46         if (!CreateRunner()) {
47             TAG_LOGE(AAFwkTag::ABILITY, "CreateRunner failed");
48             return false;
49         }
50     }
51 
52     bool ret = taskHandler_->PostTask(task, delayTime, EventQueue::Priority::LOW);
53     if (!ret) {
54         TAG_LOGE(AAFwkTag::ABILITY, "taskHandler_ PostTask failed");
55     }
56     return ret;
57 }
58 
CreateRunner()59 bool TaskHandlerClient::CreateRunner()
60 {
61     if (taskHandler_ == nullptr) {
62         std::shared_ptr<EventRunner> runner = EventRunner::Create("TaskRunner");
63         if (runner == nullptr) {
64             TAG_LOGE(AAFwkTag::ABILITY, "null runner");
65             return false;
66         }
67         taskHandler_ = std::make_shared<TaskHandler>(runner);
68         if (taskHandler_ == nullptr) {
69             TAG_LOGE(AAFwkTag::ABILITY, "null taskHandler_");
70             return false;
71         }
72     }
73     return true;
74 }
75 }  // namespace AppExecFwk
76 }  // namespace OHOS
77