Java Code Examples for java.time.Duration#compareTo()

The following examples show how to use java.time.Duration#compareTo() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void checkMaxLifetimeDuration()
{
    if ( wdStatus == HolderStatus.ACTIVE )
    {
        final Duration maxConnectionLifetime = settings.getMaxConnectionLifetime();
        if ( !allowDisconnect || maxConnectionLifetime == null )
        {
            return;
        }

        final Duration ageOfConnection = Duration.between( connectionEstablishedTime, Instant.now() );
        if ( ageOfConnection.compareTo( maxConnectionLifetime ) > 0 )
        {
            final String msg = "connection lifetime (" + ageOfConnection.toString()
                    + ") exceeded maximum configured lifetime (" + maxConnectionLifetime.toString() + ")";

            disconnectRealProvider( msg );
        }
    }
}
 
Example 2
@Schedule(
	period = 1,
	unit = ChronoUnit.SECONDS
)
public void checkMining()
{
	if (!inMlm)
	{
		return;
	}

	depositsLeft = calculateDepositsLeft();

	Instant lastPayDirtMined = session.getLastPayDirtMined();
	if (lastPayDirtMined == null)
	{
		return;
	}

	// reset recentPayDirtMined if you haven't mined anything recently
	Duration statTimeout = Duration.ofMinutes(config.statTimeout());
	Duration sinceMined = Duration.between(lastPayDirtMined, Instant.now());

	if (sinceMined.compareTo(statTimeout) >= 0)
	{
		session.resetRecent();
	}
}
 
Example 3
Source Project: logbook-kai   File: MainController.java    License: MIT License 5 votes vote down vote up
/**
 * 通知するか判断します
 *
 * @param now 残り時間
 * @param timeStamp 前回の通知の時間
 * @param remind リマインド
 */
private boolean requireNotify(Duration now, long timeStamp, boolean remind) {
    if (now.compareTo(NOTIFY) <= 0) {
        // 前回の通知からの経過時間
        Duration course = Duration.ofMillis(System.currentTimeMillis() - timeStamp);
        // リマインド間隔
        Duration interval = Duration.ofSeconds(AppConfig.get().getRemind());
        if (course.compareTo(interval) >= 0) {
            if (timeStamp == 0L || remind) {
                return true;
            }
        }
    }
    return false;
}
 
Example 4
@Schedule(
	period = 1,
	unit = ChronoUnit.SECONDS
)
void checkMining()
{
	if (!inMlm)
	{
		return;
	}

	depositsLeft = calculateDepositsLeft();

	Instant lastPayDirtMined = session.getLastPayDirtMined();
	if (lastPayDirtMined == null)
	{
		return;
	}

	// reset recentPayDirtMined if you haven't mined anything recently
	Duration statTimeout = Duration.ofMinutes(config.statTimeout());
	Duration sinceMined = Duration.between(lastPayDirtMined, Instant.now());

	if (sinceMined.compareTo(statTimeout) >= 0)
	{
		session.resetRecent();
	}
}
 
Example 5
/**
 * Constructor for an option with a given timeout. As the timeout has a coarser granularity than
 * the {@link Duration} class, values are rounded down.
 *
 * @param t the timeout time, must not be negative and must be lower than 6553.5 seconds
 */
public TcpKeepaliveOption(Duration t) {
  super(EDNSOption.Code.TCP_KEEPALIVE);
  if (t.isNegative() || t.compareTo(UPPER_LIMIT) >= 0)
    throw new IllegalArgumentException(
        "timeout must be between 0 and 6553.6 seconds (exclusively)");
  timeout = OptionalInt.of((int) t.toMillis() / 100);
}
 
Example 6
Source Project: docker-plugin   File: DockerContainerWatchdog.java    License: MIT License 5 votes vote down vote up
private void checkForTimeout(Instant startedTimestamp) {
    final Instant now = clock.instant();
    Duration runtime = Duration.between(startedTimestamp, now);

    if (runtime.compareTo(PROCESSING_TIMEOUT_IN_MS) > 0) {
        throw new WatchdogProcessingTimeout();
    }
}
 
Example 7
/**
 * This method calculates the time interval until the next event based on the
 * desired number of events before the time when interval is reset to default.
 * The return value is bounded by {@link EventTimer#defaultEventInterval} and
 * {@link EventTimer#minimumEventInterval}.
 *
 * @param eventCount
 *            number of events desired until the interval is reset to default.
 *            This is not guaranteed as the interval between events cannot be
 *            less than the minimum interval
 * @param timerResetTime
 *            time when exponential forwarding should reset to default
 *
 * @return String in HH:mm:ss format for time to next event.
 */
String timeToNextEvent(final int eventCount, final ZonedDateTime timerResetTime) {
    final ZonedDateTime currentTime = ZonedDateTime.now();

    // If there is no reset time, or if we already past the reset time,
    // return the default interval.
    if (timerResetTime == null || currentTime.compareTo(timerResetTime) > 0) {
        return defaultEventInterval;
    }

    // Calculate the interval timer based on desired event count.
    final Duration currentIntervalDuration = Duration.of(currentTime.until(timerResetTime, timeUnit), timeUnit)
            .dividedBy(eventCount);

    // Need not return interval greater than the default.
    if (currentIntervalDuration.compareTo(defaultEventIntervalDuration) > 0) {
        return defaultEventInterval;
    }

    // Should not return interval less than minimum.
    if (currentIntervalDuration.compareTo(minimumEventIntervalDuration) < 0) {
        return minimumEventInterval;
    }

    return String.format("%02d:%02d:%02d", currentIntervalDuration.toHours(),
            currentIntervalDuration.toMinutes() % 60, currentIntervalDuration.getSeconds() % 60);
}
 
Example 8
Source Project: phoebus   File: TimeTicks.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public boolean isSupportedRange(final Instant low, final Instant high)
{
    final Duration range = Duration.between(low, high);
    return low.compareTo(high) < 0  &&
           range.compareTo(min) >= 0  &&  range.compareTo(max) <= 0;
}
 
Example 9
private static Duration getNextAttemptDelay(Duration firstBackoff, Duration maxBackoff, int iteration) {
    Duration nextBackoff;
    try {
        nextBackoff = firstBackoff.multipliedBy((long) Math.pow(2, iteration));
        if (nextBackoff.compareTo(maxBackoff) > 0) {
            nextBackoff = maxBackoff;
        }
    } catch (ArithmeticException overflow) {
        nextBackoff = maxBackoff;
    }
    return nextBackoff;
}
 
Example 10
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Duration a = Duration.ofSeconds(0L, 0);
    a.compareTo(null);
}
 
Example 11
double getPlantTimeRelative()
{
	Duration duration = Duration.between(planted, Instant.now());
	return duration.compareTo(PLANT_TIME) < 0 ? (double) duration.toMillis() / PLANT_TIME.toMillis() : 1;
}
 
Example 12
@Override
public LinkedList<EligibleTaskDescriptor> getOrderedTasks(List<JobDescriptor> jobs) {
    final Date now = new Date();

    logMostLikelyMissedJobs(jobs);

    final Comparator<JobDescriptor> jobDescriptorComparator = (job1, job2) -> {

        final InternalJob internalJob1 = ((JobDescriptorImpl) job1).getInternal();
        final InternalJob internalJob2 = ((JobDescriptorImpl) job2).getInternal();
        JobPriority job1Priority = internalJob1.getPriority();
        JobPriority job2Priority = internalJob2.getPriority();
        if (!job1Priority.equals(job2Priority)) {
            // if priorities are different compare by them
            return job2Priority.compareTo(job1Priority);
        } else { // priorities are the same
            if (internalJob1.getJobDeadline().isPresent() & !internalJob2.getJobDeadline().isPresent()) {
                // job with deadline has an advanrage to the job without deadline
                return -1;
            } else if (!internalJob1.getJobDeadline().isPresent() & internalJob2.getJobDeadline().isPresent()) {
                // job with deadline has an advanrage to the job without deadline
                return 1;
            } else if (noDeadlines(internalJob1, internalJob2)) {
                // if two jobs do not have deadlines - we compare by the submitted time
                return Long.compare(internalJob1.getJobInfo().getSubmittedTime(),
                                    internalJob2.getJobInfo().getSubmittedTime());
            } else { // both dead line are present
                if (bothStarted(internalJob1, internalJob2)) {
                    // both jobs are started
                    // then compare their startTime
                    return Long.compare(internalJob1.getJobInfo().getStartTime(),
                                        internalJob2.getJobInfo().getStartTime());
                } else if (internalJob1.getJobInfo().getStartTime() >= 0 &&
                           internalJob2.getJobInfo().getStartTime() < 0) {
                    // priority to already started - internalJob1
                    return -1;
                } else if (internalJob1.getJobInfo().getStartTime() < 0 &&
                           internalJob2.getJobInfo().getStartTime() >= 0) {
                    // priority to already started - internalJob2
                    return 1;
                } else { // non of the jobs are started
                    // give a priority with the smaller interval between possible end of the job
                    // and job deadline
                    final Duration gap1 = durationBetweenFinishAndDeadline(internalJob1, now);
                    final Duration gap2 = durationBetweenFinishAndDeadline(internalJob2, now);
                    return gap1.compareTo(gap2);
                }

            }
        }
    };

    return jobs.stream()
               .sorted(jobDescriptorComparator)
               .flatMap(jobDescriptor -> jobDescriptor.getEligibleTasks().stream())
               .map(taskDescriptors -> (EligibleTaskDescriptor) taskDescriptors)
               .collect(Collectors.toCollection(LinkedList::new));
}
 
Example 13
@Override
public boolean shouldRetry(PollingStrategyContext pollingStrategyContext) {
	Duration difference = Duration.between(this.start, OffsetDateTime.now());
	return difference.compareTo(this.maxTime) < 0;
}
 
Example 14
Source Project: j2objc   File: TCKDuration.java    License: Apache License 2.0 4 votes vote down vote up
@Test(expected=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Duration a = Duration.ofSeconds(0L, 0);
    a.compareTo(null);
}
 
Example 15
Source Project: ehcache3   File: ExpiryUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isExpiryDurationInfinite(Duration duration) {
  return duration.compareTo(ExpiryPolicy.INFINITE) >= 0;
}
 
Example 16
@Test(expectedExceptions=NullPointerException.class)
public void test_compareTo_ObjectNull() {
    Duration a = Duration.ofSeconds(0L, 0);
    a.compareTo(null);
}
 
Example 17
public static boolean isShorterThan(Duration a, Duration b) {
  return a.compareTo(b) < 0;
}
 
Example 18
Source Project: bazel   File: LocalSpawnRunner.java    License: Apache License 2.0 4 votes vote down vote up
private boolean wasTimeout(Duration timeout, Duration wallTime) {
  return !timeout.isZero() && wallTime.compareTo(timeout) > 0;
}
 
Example 19
@VisibleForTesting
BigDecimal calculateSwapRate(Context context, Request request, BigDecimal dailyRate) {

    if (dailyRate == null) {
        return ZERO;
    }

    Instant now = request.getCurrentTime();

    if (now == null) {
        return ZERO;
    }

    ZonedDateTime expiry = context.getExpiry(Key.from(request));

    if (expiry == null) {
        return ZERO; // Not an expiry product.
    }

    ZonedDateTime sod = expiry.truncatedTo(ChronoUnit.DAYS);

    Duration swapFree = Duration.between(sod, expiry);

    Duration maturity = Duration.between(request.getCurrentTime(), expiry);

    if (maturity.compareTo(swapFree) < 0) {
        return ZERO; // Expiring without swap.
    }

    long swaps = maturity.toDays();

    double rate = Math.pow(ONE.add(dailyRate).doubleValue(), swaps) - 1;

    return BigDecimal.valueOf(rate).setScale(SCALE, UP);

}
 
Example 20
/**
 * Check two Durations, the second should be greater than the first or
 * within the supplied Epsilon.
 * @param d1 a Duration - presumed to be shorter
 * @param d2 a 2nd Duration - presumed to be greater (or within Epsilon)
 * @param epsilon Epsilon the amount of overlap allowed
 * @return true if d2 is greater than d1 or within epsilon, false otherwise
 */
static boolean checkEpsilon(Duration d1, Duration d2, Duration epsilon) {
    if (d1.toNanos() <= d2.toNanos()) {
        return true;
    }
    Duration diff = d1.minus(d2).abs();
    return diff.compareTo(epsilon) <= 0;
}