1 /* 2 * Copyright (C) 2023 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.settings.testutils; 18 19 import java.util.PriorityQueue; 20 import java.util.Timer; 21 import java.util.TimerTask; 22 23 /** 24 * A fake {@link Timer} that doesn't create a TimerThread which is hard to manage in test. 25 */ 26 public class FakeTimer extends Timer { 27 private final PriorityQueue<ScheduledTimerTask> mQueue = new PriorityQueue<>(); 28 FakeTimer()29 public FakeTimer() { 30 } 31 32 @Override cancel()33 public void cancel() { 34 mQueue.clear(); 35 } 36 37 @Override schedule(TimerTask task, long delay)38 public void schedule(TimerTask task, long delay) { 39 mQueue.offer(new ScheduledTimerTask(System.currentTimeMillis() + delay, task)); 40 } 41 42 /** 43 * Runs the first task in the queue if there's any. 44 */ runOneTask()45 public void runOneTask() { 46 if (mQueue.size() > 0) { 47 mQueue.poll().mTask.run(); 48 } 49 } 50 51 /** 52 * Runs all the queued tasks in order. 53 */ runAllTasks()54 public void runAllTasks() { 55 while (mQueue.size() > 0) { 56 mQueue.poll().mTask.run(); 57 } 58 } 59 60 /** 61 * Returns number of pending tasks in the timer 62 */ numOfPendingTasks()63 public int numOfPendingTasks() { 64 return mQueue.size(); 65 } 66 67 private static class ScheduledTimerTask implements Comparable<ScheduledTimerTask> { 68 final long mTimeToRunInMillisSeconds; 69 final TimerTask mTask; 70 ScheduledTimerTask(long timeToRunInMilliSeconds, TimerTask task)71 ScheduledTimerTask(long timeToRunInMilliSeconds, TimerTask task) { 72 this.mTimeToRunInMillisSeconds = timeToRunInMilliSeconds; 73 this.mTask = task; 74 } 75 76 @Override compareTo(ScheduledTimerTask other)77 public int compareTo(ScheduledTimerTask other) { 78 return Long.compare(this.mTimeToRunInMillisSeconds, other.mTimeToRunInMillisSeconds); 79 } 80 } 81 } 82