java.time.Clock.tick(Clock baseClock, Duration duration)
The method Clock.tick(Clock, Duration) returns a clock that will return instants from given baseClock truncated to given duration.
Method signature
The signature of the java.time.Clock.tick(Clock, Duration) method is as follows:
public static Clock tick( Clock baseClock, Duration tickDuration)
The method is available since Java 8.
Parameters
- Clock baseClock: not null clock to base the ticking on,
- Duration tickDuration: not null and non-negative duration of each tick
If tick duration is zero or one nanosecond then the base clock is returned, because such tick would have no effect.
Return value
Returns a clock that will instants of the underlying clock truncated to the nearest occurrences of given duration.
Exceptions
- NullPointerException: if any argument is null,
- IllegalArgumentException: if the duration is negative or has a part smaller that a millisecond such that the whole duration is not divisible into one second,
- ArithmeticException: when the duration is too large to be represented as nanoseconds.
Example usage
In the following code we use java.time.Clock.tick(Clock, Duration):
package com.farenda.java.time; import java.time.Clock; import java.time.Duration; import java.time.ZoneId; import java.util.concurrent.TimeUnit; import static java.time.Instant.ofEpochMilli; public class ClockExample { public static void main(String[] args) throws InterruptedException { Clock fixed = Clock.fixed( ofEpochMilli(12345678), ZoneId.systemDefault()); Clock tickClock = Clock.tick(fixed, Duration.ofSeconds(1)); System.out.println("Tick of fixed: " + tickClock.millis()); Clock sysClock = Clock.systemDefaultZone(); System.out.println("Sys clock millis: " + sysClock.millis()); tickClock = Clock.tick(sysClock, Duration.ofSeconds(1)); System.out.println("Tick of sys clock: " + tickClock.millis()); TimeUnit.SECONDS.sleep(2); System.out.println("Tick of sys clock: " + tickClock.millis()); } }
The above code produces the following output:
Tick of fixed: 12345000 Sys clock millis: 1464539904341 Tick of sys clock: 1464539904000 Tick of sys clock: 1464539906000