1 /* 2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. 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 #ifndef OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H 17 #define OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H 18 19 #include <atomic> 20 #include <chrono> 21 #include <condition_variable> 22 #include <functional> 23 #include <map> 24 #include <memory> 25 #include <string> 26 #include <thread> 27 #include <unordered_map> 28 29 #include "logging.h" 30 31 class ScheduleTaskManager { 32 public: 33 ScheduleTaskManager(); 34 ~ScheduleTaskManager(); 35 36 /** 37 * @brief Set up a scheduled task. 38 * @param callback Callback function 39 * @param interval Indicates the interval time, measured in milliseconds. If the 'once' parameter is set to false, 40 * an 'interval' of 0 means the task will execute immediately once and not repeat thereafter. If the 'once' 41 * parameter is set to true, the 'interval' cannot be 0. 42 * @param once Indicates whether to execute the task only once. 43 * @return If successful, it returns a timerFd greater than 0; if unsuccessful, it returns -1. 44 * @note It is crucial to ensure that the code logic executed within the provided callback function 45 * does not include any self-termination logic. 46 */ 47 int32_t ScheduleTask(const std::function<void(void)>& callback, const uint64_t interval, bool once = false); 48 /** 49 * @brief Cancel the scheduled task. 50 * @param timerFd The return value of interface ScheduleTask(). 51 * @return If the cancellation of the scheduled task is successful, it returns true; otherwise, it returns false. 52 */ 53 bool UnscheduleTask(const int32_t timerFd); 54 void Shutdown(); 55 void StartThread(); 56 57 private: 58 void ScheduleThread(); 59 void HandleSingleTask(int32_t fd, std::function<void(void)> callback); 60 bool DeleteTask(const int32_t timerFd); 61 62 private: 63 std::atomic<bool> runScheduleThread_ = true; 64 std::thread scheduleThread_; 65 std::unordered_map<int32_t, std::function<void(void)>> tasks_; 66 int32_t epollFd_{-1}; 67 int32_t stopFd_{-1}; 68 std::mutex mtx_; 69 }; 70 71 #endif // !OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H