1 /* 2 * Copyright 2025 The Netty Project 3 * 4 * The Netty Project licenses this file to you under the Apache License, 5 * version 2.0 (the "License"); you may not use this file except in compliance 6 * with the License. You may obtain a copy of the License at: 7 * 8 * https://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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations 14 * under the License. 15 */ 16 package io.netty.util.concurrent; 17 18 import java.util.concurrent.TimeUnit; 19 20 /** 21 * A nanosecond-based time source, e.g. {@link System#nanoTime()}. 22 */ 23 public interface Ticker { 24 /** 25 * Returns the singleton {@link Ticker} that returns the values from the real system clock source. 26 * However, note that this is not the same as {@link System#nanoTime()} because we apply a fixed offset 27 * to the {@link System#nanoTime() nanoTime}. 28 */ 29 static Ticker systemTicker() { 30 return SystemTicker.INSTANCE; 31 } 32 33 /** 34 * Returns a newly created mock {@link Ticker} that allows the caller control the flow of time. 35 * This can be useful when you test time-sensitive logic without waiting for too long or introducing 36 * flakiness due to non-deterministic nature of system clock. 37 */ 38 static MockTicker newMockTicker() { 39 return new DefaultMockTicker(); 40 } 41 42 /** 43 * The initial value used for delay and computations based upon a monotonic time source. 44 * @return initial value used for delay and computations based upon a monotonic time source. 45 */ 46 long initialNanoTime(); 47 48 /** 49 * The time elapsed since initialization of this class in nanoseconds. This may return a negative number just like 50 * {@link System#nanoTime()}. 51 */ 52 long nanoTime(); 53 54 /** 55 * Waits until the given amount of time goes by. 56 * 57 * @param delay the amount of delay. 58 * @param unit the {@link TimeUnit} of {@code delay}. 59 * 60 * @see Thread#sleep(long) 61 */ 62 void sleep(long delay, TimeUnit unit) throws InterruptedException; 63 64 /** 65 * Waits until the given amount of time goes by. 66 * 67 * @param delayMillis the number of milliseconds. 68 * 69 * @see Thread#sleep(long) 70 */ 71 default void sleepMillis(long delayMillis) throws InterruptedException { 72 sleep(delayMillis, TimeUnit.MILLISECONDS); 73 } 74 }