1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "chre/platform/linux/task_util/task.h"
18
19 namespace chre {
20 namespace task_manager_internal {
21
Task(const TaskFunction & func,std::chrono::milliseconds repeatInterval,uint32_t id)22 Task::Task(const TaskFunction &func, std::chrono::milliseconds repeatInterval,
23 uint32_t id)
24 : mExecutionTimestamp(std::chrono::steady_clock::now() + repeatInterval),
25 mRepeatInterval(repeatInterval),
26 mId(id),
27 mHasExecuted(false) {
28 if (func != nullptr) {
29 mFunc = func;
30 }
31 }
32
Task(const Task & rhs)33 Task::Task(const Task &rhs)
34 : mExecutionTimestamp(rhs.mExecutionTimestamp),
35 mRepeatInterval(rhs.mRepeatInterval),
36 mFunc(rhs.mFunc),
37 mId(rhs.mId),
38 mHasExecuted(rhs.mHasExecuted) {}
39
operator =(const Task & rhs)40 Task &Task::operator=(const Task &rhs) {
41 if (this != &rhs) {
42 Task rhsCopy(rhs);
43 std::swap(mExecutionTimestamp, rhsCopy.mExecutionTimestamp);
44 std::swap(mRepeatInterval, rhsCopy.mRepeatInterval);
45
46 {
47 std::lock_guard lock(mExecutionMutex);
48 std::swap(mFunc, rhsCopy.mFunc);
49 }
50
51 std::swap(mId, rhsCopy.mId);
52 std::swap(mHasExecuted, rhsCopy.mHasExecuted);
53 }
54 return *this;
55 }
56
cancel()57 void Task::cancel() {
58 std::lock_guard lock(mExecutionMutex);
59 mRepeatInterval = std::chrono::milliseconds(0);
60 mFunc.reset();
61 }
62
execute()63 void Task::execute() {
64 TaskFunction func;
65 {
66 std::lock_guard lock(mExecutionMutex);
67 if (!mFunc.has_value()) {
68 return;
69 }
70
71 func = mFunc.value();
72 }
73 func();
74 mHasExecuted = true;
75 if (isRepeating()) {
76 mExecutionTimestamp = std::chrono::steady_clock::now() + mRepeatInterval;
77 }
78 }
79
80 } // namespace task_manager_internal
81 } // namespace chre
82