• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2022 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_executor.h"
17 
18 namespace OHOS {
~TaskExecutor()19 TaskExecutor::~TaskExecutor()
20 {
21     pool_ = nullptr;
22 }
23 
GetInstance()24 TaskExecutor &TaskExecutor::GetInstance()
25 {
26     static TaskExecutor instance;
27     return instance;
28 };
29 
Execute(const Task & task)30 TaskExecutor::TaskId TaskExecutor::Execute(const Task &task)
31 {
32     if (pool_ == nullptr) {
33         GenerateExecutors();
34     }
35     if (pool_ == nullptr) {
36         return INVALID_TASK_ID;
37     }
38     return pool_->Execute(std::move(task));
39 }
40 
Schedule(Duration delay,const Task & task,Duration interval,uint64_t times)41 TaskExecutor::TaskId TaskExecutor::Schedule(Duration delay, const Task &task, Duration interval, uint64_t times)
42 {
43     if (pool_ == nullptr) {
44         GenerateExecutors();
45     }
46     if (pool_ == nullptr) {
47         return INVALID_TASK_ID;
48     }
49     return pool_->Schedule(task, delay, interval, times);
50 }
51 
Remove(TaskExecutor::TaskId taskId,bool wait)52 bool TaskExecutor::Remove(TaskExecutor::TaskId taskId, bool wait)
53 {
54     if (pool_ == nullptr) {
55         return false;
56     }
57     return pool_->Remove(taskId, wait);
58 }
59 
Reset(TaskExecutor::TaskId taskId,Duration interval)60 TaskExecutor::TaskId TaskExecutor::Reset(TaskExecutor::TaskId taskId, Duration interval)
61 {
62     if (pool_ == nullptr) {
63         return INVALID_TASK_ID;
64     }
65     return pool_->Reset(taskId, interval);
66 }
67 
SetExecutors(std::shared_ptr<ExecutorPool> executors)68 void TaskExecutor::SetExecutors(std::shared_ptr<ExecutorPool> executors)
69 {
70     std::lock_guard<decltype(mtx_)> lock(mtx_);
71     if (pool_ == nullptr) {
72         pool_ = std::move(executors);
73     }
74 }
75 
GenerateExecutors()76 void TaskExecutor::GenerateExecutors()
77 {
78     std::lock_guard<decltype(mtx_)> lock(mtx_);
79     if (pool_ == nullptr) {
80         pool_ = std::make_shared<ExecutorPool>(MAX_THREADS, MIN_THREADS);
81     }
82 }
83 } // namespace OHOS
84