Example usage for java.time Duration between

List of usage examples for java.time Duration between

Introduction

In this page you can find the example usage for java.time Duration between.

Prototype

public static Duration between(Temporal startInclusive, Temporal endExclusive) 

Source Link

Document

Obtains a Duration representing the duration between two temporal objects.

Usage

From source file:com.netflix.spinnaker.echo.pipelinetriggers.health.MonitoredPollerHealth.java

private void polledRecently(Health.Builder builder) {
    Instant lastPollTimestamp = poller.getLastPollTimestamp();
    if (lastPollTimestamp == null) {
        builder.unknown();/*from ww w .j  av  a  2  s  .  co m*/
    } else {
        val timeSinceLastPoll = Duration.between(lastPollTimestamp, now());
        builder.withDetail("last.polled",
                formatDurationWords(timeSinceLastPoll.toMillis(), true, true) + " ago");
        builder.withDetail("last.polled.at",
                ISO_LOCAL_DATE_TIME.format(lastPollTimestamp.atZone(ZoneId.systemDefault())));
        if (timeSinceLastPoll.compareTo(Duration.of(poller.getPollingIntervalSeconds() * 2, SECONDS)) <= 0) {
            builder.up();
        } else {
            builder.down();
        }
    }
}

From source file:de.bytefish.fcmjava.client.http.apache.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }/*from  w w  w  .java  2 s .c  om*/

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}

From source file:de.bytefish.fcmjava.client.interceptors.response.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<ZonedDateTime>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }/*from  w  w w . j av  a2 s . co m*/

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}

From source file:com.pepaproch.gtswsdl.client.RateLimitTest.java

@Test
public void testCOnsumeSLotAsync() {
    RateLimit rate = new RateLimit(5, 10, ChronoUnit.SECONDS);
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    final AtomicInteger cc = new AtomicInteger(0);
    Instant start = Instant.now();
    final Instant[] end = new Instant[1];

    Runnable r = () -> {// ww  w  .j a v  a  2 s  .com
        for (int i = 0; i < 21; i++) {
            addTask(cc, scheduler, rate, end);
        }
    };
    Runnable r1 = () -> {
        for (int i = 0; i < 9; i++) {
            addTask(cc, scheduler, rate, end);

        }
    };

    r1.run();
    r.run();

    try {

        scheduler.awaitTermination(5, TimeUnit.SECONDS);

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(Duration.between(start, end[0]).toMillis());
}

From source file:com.peso.Workout.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w  .j a  v  a  2 s.  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean bError = false;
    String mensajeError = "";

    String nombre = "";
    String peso = "";
    String workout = "";
    LocalDateTime ultimaLlamada = null;
    LocalDateTime ahora = null;
    LocalDateTime lesionado = null;

    //Errores
    if (request.getSession().getAttribute("nombre") == null) {
        mensajeError = "no hay nombre resgistrado";
        bError = true;
    } else {
        workout = request.getParameter("workout");

        if (workout == null) {
            mensajeError = "falta el parametro workout";
            bError = true;
        } else if (!StringUtils.isNumeric(workout)) {
            mensajeError = "workout debe de ser numrico";
            bError = true;
        }
    }
    if (!bError) {
        //Registrar el usuario
        nombre = (String) request.getSession().getAttribute("nombre");
        peso = (String) request.getSession().getAttribute("peso");
        ahora = LocalDateTime.now();
        ultimaLlamada = (LocalDateTime) request.getSession().getAttribute("ultimaLlamada");
        if (ultimaLlamada == null) {
            ultimaLlamada = LocalDateTime.now();
        }
        //engordar cada 10 segundos, tiempo entre llamadas.
        Duration segundos = Duration.between(ultimaLlamada, ahora);
        int iPeso = NumberUtils.toInt(peso);
        iPeso += (segundos.getSeconds() / 10);

        //mirar si lesion
        lesionado = (LocalDateTime) request.getSession().getAttribute("lesionado");
        Duration segundosLesion = null;

        // si hay lesion esperar tiempo
        if (lesionado != null) {
            segundosLesion = Duration.between(lesionado, ahora);
            if (segundosLesion.getSeconds() >= 30) {
                // se le quita la lesion
                request.getSession().setAttribute("lesionado", null);
            }
            request.setAttribute("lesionado", (30 - segundosLesion.getSeconds()) + "");
        } else//si han pasado menos de 5 seg se lesiona
        {
            if (segundos.getSeconds() <= 5) {
                request.getSession().setAttribute("lesionado", ahora);
            } else {
                //si no la hay adelgaza el tiempo requerido.
                int kilosAdelgazar = (NumberUtils.toInt(workout) / 30);
                kilosAdelgazar *= (int) (0.2 * iPeso);
                iPeso -= kilosAdelgazar;
            }
        }
        peso = iPeso + "";
        request.getSession().setAttribute("peso", peso);
        request.getSession().setAttribute("ultimaLlamada", ahora);

        request.setAttribute("nombre", nombre);
        request.setAttribute("peso", peso);
        request.getRequestDispatcher("/workout.jsp").forward(request, response);
    } else {
        request.setAttribute(Constantes.ATRIBUTO_ERROR, mensajeError);
        request.getRequestDispatcher(Constantes.PAGINA_ERROR).forward(request, response);
    }
}

From source file:com.speedment.examples.social.JSONImage.java

@Override
public int compareTo(JSONImage o) {
    return (int) Duration.between(o.uploaded, uploaded).getSeconds();
}

From source file:keepinchecker.utility.EmailUtilities.java

protected static boolean hasScheduledEmailBeenSent(User user) {
    String emailFrequency = user.getEmailFrequency();
    long emailLastSentDate = user.getEmailLastSentDate();
    Duration timeBetweenLastEmailSentToNow = Duration.between(new Date(emailLastSentDate).toInstant(),
            Instant.now());/*from   w w w.  j  ava  2  s.c om*/

    if (StringUtils.equals(emailFrequency, User.EMAIL_FREQUENCY_WEEKLY)
            && timeBetweenLastEmailSentToNow.toDays() < 7) {
        return true;
    } else if (StringUtils.equals(emailFrequency, User.EMAIL_FREQUENCY_DAILY)
            && timeBetweenLastEmailSentToNow.toDays() < 1) {
        return true;
    }

    return false;
}

From source file:com.example.oauth.AccessToken.java

@Override
public int getExpiresIn() {
    final OffsetDateTime now = OffsetDateTime.now();
    final Duration expiredIn = Duration.between(now, expiration);
    return (int) expiredIn.get(ChronoUnit.SECONDS);
}

From source file:com.serphacker.serposcope.models.base.Run.java

protected long getRemainingTimeMs(LocalDateTime now) {
    if (finished != null || started == null || progress == 0 || progress == 100) {
        return 0;
    }//from   w  ww. j a v  a  2s  .c  o m

    long duration = (Math.abs(Duration.between(started, now).toMillis()) / 1000l) * 1000l;
    return (duration / progress) * (100 - progress);
}

From source file:net.havox.times.model.times.impl.WorkUnitImpl.java

@Override
public Duration getWorkUnitDuration() {
    if ((this.workUnitStart == null) || (this.workUnitEnd == null)) {
        String message = "Neigther the 'start'=" + this.workUnitStart + " nor the 'end'=" + this.workUnitEnd
                + " parameter is allowed to be NULL.";
        throw new GuruMeditationWarning(ILLEGAL_ARGUMENT, message);
    }/*from w w w .  j  a va 2 s .co m*/

    return Duration.between(this.workUnitStart, this.workUnitEnd);
}