blob: 5a76dbc4ff1c0946732c337f03ad55c91094efff [file] [log] [blame]
Ana Krulecfb772822018-11-30 10:44:07 +01001/*
2 * Copyright 2018 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 "IdleTimer.h"
18
19#include <chrono>
20#include <thread>
21
22namespace android {
23namespace scheduler {
24
25IdleTimer::IdleTimer(const Interval& interval, const TimeoutCallback& timeoutCallback)
26 : mInterval(interval), mTimeoutCallback(timeoutCallback) {}
27
28IdleTimer::~IdleTimer() {
29 stop();
30}
31
32void IdleTimer::start() {
33 {
34 std::lock_guard<std::mutex> lock(mMutex);
35 mState = TimerState::RESET;
36 }
37 mThread = std::thread(&IdleTimer::loop, this);
38}
39
40void IdleTimer::stop() {
41 {
42 std::lock_guard<std::mutex> lock(mMutex);
43 mState = TimerState::STOPPED;
44 }
45 mCondition.notify_all();
46 if (mThread.joinable()) {
47 mThread.join();
48 }
49}
50
51void IdleTimer::loop() {
52 std::lock_guard<std::mutex> lock(mMutex);
53 while (mState != TimerState::STOPPED) {
54 if (mState == TimerState::IDLE) {
55 mCondition.wait(mMutex);
56 } else if (mState == TimerState::RESET) {
57 mState = TimerState::WAITING;
58 if (mCondition.wait_for(mMutex, mInterval) == std::cv_status::timeout) {
59 if (mTimeoutCallback) {
60 mTimeoutCallback();
61 }
62 }
63 if (mState == TimerState::WAITING) {
64 mState = TimerState::IDLE;
65 }
66 }
67 }
68}
69
70void IdleTimer::reset() {
71 {
72 std::lock_guard<std::mutex> lock(mMutex);
73 mState = TimerState::RESET;
74 }
75 mCondition.notify_all();
76}
77
78} // namespace scheduler
79} // namespace android