Java TimeUnit Calculate resetWithClockStep(long clockStep, TimeUnit clockStepUnit)

Here you can find the source of resetWithClockStep(long clockStep, TimeUnit clockStepUnit)

Description

Reset the clock to a known start point, then set the clock step.

License

Apache License

Parameter

Parameter Description
clockStep amount to increment clock by on each lookup.
clockStepUnit time unit for clockStep .

Declaration

public static synchronized void resetWithClockStep(long clockStep, TimeUnit clockStepUnit) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeUtils.MillisProvider;
import org.joda.time.DateTimeZone;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class Main {
    private static Long clockStepMs;
    private static AtomicLong clockMs;

    /**/*from ww w .  j ava  2s .  c  om*/
     * Reset the clock to a known start point, then set the clock step.
     * <p>
     * The clock is initially set to 2009/09/30 17:00:00 -0400.
     *
     * @param clockStep amount to increment clock by on each lookup.
     * @param clockStepUnit time unit for {@code clockStep}.
     */
    public static synchronized void resetWithClockStep(long clockStep, TimeUnit clockStepUnit) {
        // Set an arbitrary start point so tests are more repeatable.
        clockMs = new AtomicLong(new DateTime(2009, 9, 30, 17, 0, 0, DateTimeZone.forOffsetHours(-4)).getMillis());
        setClockStep(clockStep, clockStepUnit);
    }

    /**
     * Set the clock step used by {@link com.google.gerrit.common.TimeUtil}.
     *
     * @param clockStep amount to increment clock by on each lookup.
     * @param clockStepUnit time unit for {@code clockStep}.
     */
    public static synchronized void setClockStep(long clockStep, TimeUnit clockStepUnit) {
        checkState(clockMs != null, "call resetWithClockStep first");
        clockStepMs = MILLISECONDS.convert(clockStep, clockStepUnit);
        DateTimeUtils.setCurrentMillisProvider(new MillisProvider() {
            @Override
            public long getMillis() {
                return clockMs.getAndAdd(clockStepMs);
            }
        });
    }
}

Related

  1. parseTimeUnit(final String unit)
  2. parseTimeUnit(Object property, TimeUnit defaultValue)
  3. pause(long duration, TimeUnit unit)
  4. printTime(long time, TimeUnit unit)
  5. randomSleep(int duration, TimeUnit timeUnit)
  6. run(final Runnable runnable, long timeout, TimeUnit unit)
  7. shortName(TimeUnit unit)
  8. sleep(int duration, TimeUnit unit)
  9. sleep(long duration, TimeUnit timeUnit)