blob: e975e658dd8e3bd1c8accf2bee7ffbe52a523274 [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) {
Lloyd Pique1f9f1a42019-01-31 13:04:00 -080057 auto triggerTime = std::chrono::steady_clock::now() + mInterval;
Ana Krulecfb772822018-11-30 10:44:07 +010058 mState = TimerState::WAITING;
Lloyd Pique1f9f1a42019-01-31 13:04:00 -080059 while (mState == TimerState::WAITING) {
60 constexpr auto zero = std::chrono::steady_clock::duration::zero();
61 auto waitTime = triggerTime - std::chrono::steady_clock::now();
62 if (waitTime > zero) mCondition.wait_for(mMutex, waitTime);
63 if (mState == TimerState::WAITING &&
64 (triggerTime - std::chrono::steady_clock::now()) <= zero) {
65 if (mTimeoutCallback) {
66 mTimeoutCallback();
67 }
68
69 mState = TimerState::IDLE;
Ana Krulecfb772822018-11-30 10:44:07 +010070 }
71 }
Ana Krulecfb772822018-11-30 10:44:07 +010072 }
73 }
Lloyd Pique1f9f1a42019-01-31 13:04:00 -080074} // namespace scheduler
Ana Krulecfb772822018-11-30 10:44:07 +010075
76void IdleTimer::reset() {
77 {
78 std::lock_guard<std::mutex> lock(mMutex);
79 mState = TimerState::RESET;
80 }
81 mCondition.notify_all();
82}
83
84} // namespace scheduler
85} // namespace android