1 /*
2 * Copyright (C) 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 "component_test/test_task_scheduler.h"
17
18 #include "core/common/task_runner_adapter.h"
19 #include "core/common/task_runner_adapter_factory.h"
20
21 namespace OHOS::Ace::ComponentTest {
22
Initialize(RefPtr<IdleWatcher> idleWatcher, RefPtr<TaskExecutor> taskExecutor)23 void TestTaskScheduler::Initialize(RefPtr<IdleWatcher> idleWatcher, RefPtr<TaskExecutor> taskExecutor)
24 {
25 idleWatcher_ = idleWatcher;
26 taskExecutor_ = taskExecutor;
27 if (!testTaskSchedulerThread_) {
28 testTaskSchedulerThread_ = TaskRunnerAdapterFactory::Create(false, "TestTaskScheduler");
29 }
30 }
31
Destroy()32 void TestTaskScheduler::Destroy()
33 {
34 if (testTaskSchedulerThread_) {
35 testTaskSchedulerThread_.Reset();
36 }
37 }
38
PushTask(std::function<void(void*)>&& task, std::function<void(void*)>&& onFinish, TaskExecutor::TaskType taskType, void* data, uint32_t delay)39 void TestTaskScheduler::PushTask(std::function<void(void*)>&& task, std::function<void(void*)>&& onFinish,
40 TaskExecutor::TaskType taskType, void* data, uint32_t delay)
41 {
42 std::function<void()> task_;
43 std::function<void()> finish_;
44 if (onFinish) {
45 finish_ = [this, onFinish = std::move(onFinish), taskType, data]() {
46 idleWatcher_->RequestNextIdleStatusNotification([this, onFinish = std::move(onFinish), taskType, data]() {
47 taskExecutor_->PostTask([data, onFinish = move(onFinish)]() { onFinish(data); }, taskType, {});
48 });
49 };
50 } else {
51 finish_ = []() {};
52 }
53 if (task) {
54 task_ = [data, task = std::move(task), finish = std::move(finish_)]() {
55 task(data);
56 finish();
57 };
58 } else {
59 task_ = [finish = std::move(finish_)]() { finish(); };
60 }
61
62 testTaskSchedulerThread_->PostDelayedTask(
63 [this, task = std::move(task_), taskType]() {
64 idleWatcher_->RequestNextIdleStatusNotification(
65 [this, task = std::move(task), taskType]() {
66 taskExecutor_->PostTask([task = std::move(task)]() { task(); }, taskType, {});
67 },
68 true);
69 },
70 delay, {});
71 }
72 } // namespace OHOS::Ace::ComponentTest
73