Java Utililty Methods TimeUnit Calculate

List of utility methods to do TimeUnit Calculate

Description

The list of methods to do TimeUnit Calculate are organized into topic(s).

Method

intrandomSleep(int duration, TimeUnit timeUnit)
random Sleep
int sleepTime = ThreadLocalRandom.current().nextInt(duration);
try {
    timeUnit.sleep(sleepTime);
} catch (InterruptedException e) {
    Throwables.propagate(e);
return sleepTime;
voidresetWithClockStep(long clockStep, TimeUnit clockStepUnit)
Reset the clock to a known start point, then set the clock step.
clockMs = new AtomicLong(new DateTime(2009, 9, 30, 17, 0, 0, DateTimeZone.forOffsetHours(-4)).getMillis());
setClockStep(clockStep, clockStepUnit);
booleanrun(final Runnable runnable, long timeout, TimeUnit unit)
Executes given Runnable with timeout.
final boolean done[] = { false };
Thread thread = new Thread("TimeboxUtils.run") {
    @Override
    public void run() {
        runnable.run();
        done[0] = true;
};
...
StringshortName(TimeUnit unit)
short Name
switch (unit) {
case NANOSECONDS:
    return "ns";
case MICROSECONDS:
    return "us";
case MILLISECONDS:
    return "ms";
case SECONDS:
...
voidsleep(int duration, TimeUnit unit)
sleep
try {
    unit.sleep(duration);
} catch (InterruptedException e) {
voidsleep(long duration, TimeUnit timeUnit)
A convenience version of Thread.sleep that uses TimeUnits instead of raw milliseconds and swallows interrupted exceptions
try {
    Thread.sleep(toMillis(duration, timeUnit));
} catch (InterruptedException ex) {
    System.out.println("sleep interrupted: " + ex.getMessage());
voidsleep(long duration, TimeUnit timeUnit)
Sleeps the current thread for the given duration.
try {
    Thread.sleep(timeUnit.toMillis(duration));
} catch (InterruptedException ignore) {
voidsleep(long pTime, TimeUnit pTimeUnit)
sleep
final long lStart = System.nanoTime();
long lDeadlineInNanos = lStart + pTimeUnit.toNanos(pTime);
boolean lSleepTimeBelowMillisecond = pTimeUnit.toMillis(pTime) == 0;
long lNanoTime;
while ((lNanoTime = System.nanoTime()) < lDeadlineInNanos) {
    try {
        if (lSleepTimeBelowMillisecond) {
            long lTimeToWaitInNanos = 3 * (lDeadlineInNanos - lNanoTime) / 4;
...
voidsleep(TimeUnit timeUnit, long duration)
sleep
try {
    timeUnit.sleep(duration);
} catch (InterruptedException ex) {
    Thread.currentThread().interrupt();
voidsleep(TimeUnit unit, long length)
sleep
boolean interrupted = false;
try {
    long duration = TimeUnit.MILLISECONDS.convert(length, unit);
    while (duration > 0) {
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(duration);
        } catch (InterruptedException e) {
...