xref: /aosp_15_r20/system/chre/platform/linux/task_util/task.cc (revision 84e339476a462649f82315436d70fd732297a399)
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::nanoseconds intervalOrDelay,uint32_t id,bool isOneShot)22 Task::Task(const TaskFunction &func, std::chrono::nanoseconds intervalOrDelay,
23            uint32_t id, bool isOneShot)
24     : mExecutionTimestamp(std::chrono::steady_clock::now() + intervalOrDelay),
25       mRepeatInterval(isOneShot ? std::chrono::nanoseconds(0)
26                                 : intervalOrDelay),
27       mFunc(func),
28       mId(id),
29       mHasExecuted(false) {}
30 
Task(const Task & rhs)31 Task::Task(const Task &rhs)
32     : mExecutionTimestamp(rhs.mExecutionTimestamp),
33       mRepeatInterval(rhs.mRepeatInterval),
34       mFunc(rhs.mFunc),
35       mId(rhs.mId),
36       mHasExecuted(rhs.mHasExecuted) {}
37 
operator =(const Task & rhs)38 Task &Task::operator=(const Task &rhs) {
39   if (this != &rhs) {
40     Task rhsCopy(rhs);
41     std::swap(mExecutionTimestamp, rhsCopy.mExecutionTimestamp);
42     std::swap(mRepeatInterval, rhsCopy.mRepeatInterval);
43 
44     {
45       std::lock_guard lock(mExecutionMutex);
46       std::swap(mFunc, rhsCopy.mFunc);
47     }
48 
49     std::swap(mId, rhsCopy.mId);
50     std::swap(mHasExecuted, rhsCopy.mHasExecuted);
51   }
52   return *this;
53 }
54 
cancel()55 void Task::cancel() {
56   std::lock_guard lock(mExecutionMutex);
57   mRepeatInterval = std::chrono::nanoseconds(0);
58   mFunc.reset();
59 }
60 
execute()61 void Task::execute() {
62   TaskFunction func;
63   {
64     std::lock_guard lock(mExecutionMutex);
65     if (!mFunc.has_value()) {
66       return;
67     }
68 
69     func = mFunc.value();
70   }
71   func();
72   mHasExecuted = true;
73   if (isRepeating()) {
74     mExecutionTimestamp = std::chrono::steady_clock::now() + mRepeatInterval;
75   }
76 }
77 
78 }  // namespace task_manager_internal
79 }  // namespace chre
80