Example usage for java.util.concurrent TimeUnit toSeconds

List of usage examples for java.util.concurrent TimeUnit toSeconds

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit toSeconds.

Prototype

public long toSeconds(long duration) 

Source Link

Document

Equivalent to #convert(long,TimeUnit) SECONDS.convert(duration, this) .

Usage

From source file:Main.java

public static void main(String[] args) {
    TimeUnit tu = TimeUnit.DAYS;

    System.out.println(tu.toDays(1));
    System.out.println(tu.toHours(1));
    System.out.println(tu.toSeconds(1));

}

From source file:Main.java

public static String getReadableSpeed(long downloaded, long timespend, TimeUnit timeUnit) {
    long span = timeUnit.toSeconds(timespend);
    if (timespend * span == 0) {
        return "0";
    }//from  ww  w. j a v a 2 s  . c  om
    return getReadableSize(downloaded / span, true) + "/s";
}

From source file:org.apache.solr.cloud.autoscaling.ExecutePlanAction.java

static CollectionAdminRequest.RequestStatusResponse waitForTaskToFinish(SolrCloudManager dataProvider,
        String requestId, long duration, TimeUnit timeUnit) throws IOException, InterruptedException {
    long timeoutSeconds = timeUnit.toSeconds(duration);
    RequestStatusState state = RequestStatusState.NOT_FOUND;
    CollectionAdminRequest.RequestStatusResponse statusResponse = null;
    for (int i = 0; i < timeoutSeconds; i++) {
        try {//w w w  .j av  a  2 s  .  c o m
            statusResponse = (CollectionAdminRequest.RequestStatusResponse) dataProvider
                    .request(CollectionAdminRequest.requestStatus(requestId));
            state = statusResponse.getRequestStatus();
            if (state == RequestStatusState.COMPLETED || state == RequestStatusState.FAILED) {
                log.info("Task with requestId={} finished with state={} in {}s", requestId, state, i * 5);
                dataProvider.request(CollectionAdminRequest.deleteAsyncId(requestId));
                return statusResponse;
            } else if (state == RequestStatusState.NOT_FOUND) {
                // the request for this id was never actually submitted! no harm done, just bail out
                log.warn("Task with requestId={} was not found on overseer", requestId);
                dataProvider.request(CollectionAdminRequest.deleteAsyncId(requestId));
                return statusResponse;
            }
        } catch (Exception e) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause instanceof IllegalStateException
                    && rootCause.getMessage().contains("Connection pool shut down")) {
                throw e;
            }
            if (rootCause instanceof TimeoutException
                    && rootCause.getMessage().contains("Could not connect to ZooKeeper")) {
                throw e;
            }
            if (rootCause instanceof SolrServerException) {
                throw e;
            }
            log.error("Unexpected Exception while querying status of requestId=" + requestId, e);
        }
        if (i > 0 && i % 5 == 0) {
            log.debug("Task with requestId={} still not complete after {}s. Last state={}", requestId, i * 5,
                    state);
        }
        TimeUnit.SECONDS.sleep(5);
    }
    log.debug("Task with requestId={} did not complete within 5 minutes. Last state={}", requestId, state);
    return statusResponse;
}

From source file:com.amazon.carbonado.repo.jdbc.JDBCStorage.java

static PreparedStatement prepareStatement(Connection con, String sql, Query.Controller controller)
        throws SQLException {
    PreparedStatement ps = con.prepareStatement(sql);

    if (controller != null) {
        long timeout = controller.getTimeout();
        if (timeout >= 0) {
            TimeUnit unit = controller.getTimeoutUnit();
            if (unit != null) {
                long seconds = unit.toSeconds(timeout);
                int intSeconds = seconds <= 0 ? 1 : (seconds <= Integer.MAX_VALUE ? ((int) seconds) : 0);
                ps.setQueryTimeout(intSeconds);
            }/*from  w  w w  . ja  va 2 s.c om*/
        }
    }

    return ps;
}

From source file:com.brightcove.player.samples.offlineplayback.VideoListAdapter.java

/**
 * Converts the given duration into a time span string.
 *
 * @param duration elapsed time as number of milliseconds.
 * @return the formatted time span string.
 *///from w  w w .j  ava  2 s .c  o  m
@NonNull
public static String millisecondsToString(long duration) {
    final TimeUnit scale = TimeUnit.MILLISECONDS;

    StringBuilder builder = new StringBuilder();
    long days = scale.toDays(duration);
    duration -= TimeUnit.DAYS.toMillis(days);
    if (days > 0) {
        builder.append(days);
        builder.append(days > 1 ? " days " : " day ");
    }

    long hours = scale.toHours(duration);
    duration -= TimeUnit.HOURS.toMillis(hours);
    if (hours > 0) {
        builder.append(String.format("%02d:", hours));
    }

    long minutes = scale.toMinutes(duration);
    duration -= TimeUnit.MINUTES.toMillis(minutes);

    long seconds = scale.toSeconds(duration);
    builder.append(String.format("%02d:%02d", minutes, seconds));

    return builder.toString();
}

From source file:org.apache.pulsar.client.impl.ClientBuilderImpl.java

@Override
public ClientBuilder statsInterval(long statsInterval, TimeUnit unit) {
    conf.setStatsIntervalSeconds(unit.toSeconds(statsInterval));
    return this;
}

From source file:org.apache.pulsar.client.impl.ClientBuilderImpl.java

@Override
public ClientBuilder keepAliveInterval(int keepAliveIntervalSeconds, TimeUnit unit) {
    conf.setKeepAliveIntervalSeconds((int) unit.toSeconds(keepAliveIntervalSeconds));
    return this;
}

From source file:net.dv8tion.jda.core.requests.restaction.InviteAction.java

/**
 * Sets the max age for the invite. Set this to {@code 0} if the invite should never expire. Default is {@code 86400} (24 hours).
 * {@code null} will reset this to the default value.
 *
 * @param  maxAge//from  w  w w. ja va2  s  .com
 *         The max age for this invite or {@code null} to use the default value.
 * @param  timeUnit
 *         The {@link java.util.concurrent.TimeUnit TimeUnit} type of {@code maxAge}.
 *
 * @throws IllegalArgumentException
 *         If maxAge is negative or maxAge is positive and timeUnit is null.
 *
 * @return The current InviteAction for chaining.
 */
@CheckReturnValue
public final InviteAction setMaxAge(final Long maxAge, final TimeUnit timeUnit) {
    if (maxAge == null)
        return this.setMaxAge(null);

    Checks.notNegative(maxAge, "maxAge");
    Checks.notNull(timeUnit, "timeUnit");

    return this.setMaxAge(Math.toIntExact(timeUnit.toSeconds(maxAge)));
}

From source file:com.sangupta.dryrun.redis.OpsForValue.java

@Override
public void set(K key, V value, long timeout, TimeUnit unit) {
    if (TimeUnit.MILLISECONDS.equals(unit)) {
        int millis = ((Long) timeout).intValue();
        this.bridge.psetex(rawKey(key), millis, rawValue(value));
        return;/*from   w  ww  .  j  a v  a2s  .  c om*/
    }

    Long seconds = unit.toSeconds(timeout);
    this.bridge.setex(rawKey(key), seconds.intValue(), rawValue(value));
}

From source file:AlternateDeadlockDetectingLock.java

public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
    if (DDLFastFail && DDLdeadlockDETECTED) {
        throw new DeadlockDetectedException("EARILER DEADLOCK DETECTED");
    }/*from   w w w.ja v  a  2 s  .  co  m*/

    // Perform operation as a soft wait
    if (unit.toSeconds(time) < DDLHWSWTime) {
        return super.tryLock(time, unit);
    }

    // Note: Owner can't change if current thread is owner. It is
    //       not guaranteed otherwise. Other owners can change due to
    //       condition variables.
    if (isHeldByCurrentThread()) {
        if (debugging)
            System.out.println("Already Own Lock");
        try {
            return super.tryLock(time, unit);
        } finally {
            freeIfHardwait(hardwaitingThreads, Thread.currentThread());
        }
    }

    // Note: The wait list must be marked before it is tested because
    //       there is a race condition between lock() method calls.
    markAsHardwait(hardwaitingThreads, Thread.currentThread());
    if (canThreadWaitOnLock(Thread.currentThread(), this)) {
        if (debugging)
            System.out.println("Waiting For Lock");
        try {
            return super.tryLock(time, unit);
        } finally {
            freeIfHardwait(hardwaitingThreads, Thread.currentThread());
            if (debugging)
                System.out.println("Got New Lock");
        }
    } else {
        DDLdeadlockDETECTED = true;
        if (DDLCleanUp)
            freeIfHardwait(hardwaitingThreads, Thread.currentThread());
        throw new DeadlockDetectedException("DEADLOCK DETECTED");
    }
}