blob: acf0b1696b89c2006300a88f9ebc87e693fdecf8 [file] [log] [blame]
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -08001/*
2 * Copyright (C) 2021 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#pragma once
18
19#include <condition_variable>
20#include <functional>
21#include <map>
22#include <mutex>
23#include <thread>
24
25#include <android-base/thread_annotations.h>
26
27namespace android {
28
29/**
30 * A thread for deferred execution of tasks, with cancellation.
31 */
32class TimerThread {
33 public:
34 using Handle = std::chrono::steady_clock::time_point;
35
36 TimerThread();
37 ~TimerThread();
38
39 /**
40 * Schedule a task to be executed in the future (`timeout` duration from now).
41 * Returns a handle that can be used for cancellation.
42 */
43 template <typename R, typename P>
44 Handle scheduleTask(std::function<void()>&& func, std::chrono::duration<R, P> timeout) {
45 auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
46 return scheduleTaskAtDeadline(std::move(func), deadline);
47 }
48
49 /**
50 * Cancel a task, previously scheduled with scheduleTask().
Andy Hung5c6d68a2022-03-09 21:54:59 -080051 * If the task has already executed, this is a no-op and returns false.
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080052 */
Andy Hung5c6d68a2022-03-09 21:54:59 -080053 bool cancelTask(Handle handle);
Ytai Ben-Tsvi1ea62c92021-11-10 14:38:27 -080054
55 private:
56 using TimePoint = std::chrono::steady_clock::time_point;
57
58 std::condition_variable mCond;
59 std::mutex mMutex;
60 std::thread mThread;
61 std::map<TimePoint, std::function<void()>> mMonitorRequests GUARDED_BY(mMutex);
62 bool mShouldExit GUARDED_BY(mMutex) = false;
63
64 void threadFunc();
65 Handle scheduleTaskAtDeadline(std::function<void()>&& func, TimePoint deadline);
66};
67
68} // namespace android