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