1 /*
2  * Copyright (C) 2016 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 package com.android.car.systeminterface;
18 
19 import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
20 
21 import android.os.SystemClock;
22 
23 import com.android.internal.annotations.GuardedBy;
24 
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.concurrent.TimeUnit;
27 
28 /**
29  * Interface that abstracts time operations
30  */
31 public interface TimeInterface {
32     public static final boolean INCLUDE_DEEP_SLEEP_TIME = true;
33     public static final boolean EXCLUDE_DEEP_SLEEP_TIME = false;
34 
getUptime()35     default long getUptime() {
36         return getUptime(EXCLUDE_DEEP_SLEEP_TIME);
37     }
getUptime(boolean includeDeepSleepTime)38     default long getUptime(boolean includeDeepSleepTime) {
39         return includeDeepSleepTime ?
40             SystemClock.elapsedRealtime() :
41             SystemClock.uptimeMillis();
42     }
43 
scheduleAction(Runnable r, long delayMs)44     void scheduleAction(Runnable r, long delayMs);
cancelAllActions()45     void cancelAllActions();
46 
47     class DefaultImpl implements TimeInterface {
48         private final Object mLock = new Object();
49 
50         @GuardedBy("mLock")
51         private ScheduledExecutorService mExecutor;
52 
53         @Override
scheduleAction(Runnable r, long delayMs)54         public void scheduleAction(Runnable r, long delayMs) {
55             ScheduledExecutorService executor;
56             synchronized (mLock) {
57                 executor = mExecutor;
58                 if (executor == null) {
59                     executor = newSingleThreadScheduledExecutor();
60                     mExecutor = executor;
61                 }
62             }
63             executor.scheduleAtFixedRate(r, delayMs, delayMs, TimeUnit.MILLISECONDS);
64         }
65 
66         @Override
cancelAllActions()67         public void cancelAllActions() {
68             ScheduledExecutorService executor;
69             synchronized (mLock) {
70                 executor = mExecutor;
71                 mExecutor = null;
72             }
73             if (executor != null) {
74                 executor.shutdownNow();
75             }
76         }
77     }
78 }
79