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
31class ScheduleTaskManager {
32public:
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                         bool block = true);
49    /**
50     * @brief Cancel the scheduled task.
51     * @param timerFd The return value of interface ScheduleTask().
52     * @return If the cancellation of the scheduled task is successful, it returns true; otherwise, it returns false.
53     */
54    bool UnscheduleTask(const int32_t timerFd);
55    bool UnscheduleTaskLockless(const int32_t timerFd);
56    void Shutdown();
57    void StartThread();
58
59private:
60    void ScheduleThread();
61    void HandleSingleTask(int32_t fd, std::function<void(void)> callback);
62    bool DeleteTask(const int32_t timerFd);
63
64private:
65    std::atomic<bool> runScheduleThread_ = true;
66    std::thread scheduleThread_;
67    std::unordered_map<int32_t, std::function<void(void)>> tasks_;
68    int32_t epollFd_{-1};
69    int32_t stopFd_{-1};
70    std::mutex mtx_;
71};
72
73#endif // !OHOS_PROFILER_SCHEDULE_TASK_MANAGER_H