Java Code Examples for java.util.concurrent.TimeUnit#toSeconds()

The following examples show how to use java.util.concurrent.TimeUnit#toSeconds() . 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
Source File: MetricReporter.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
private MetricReporter(MetricRegistry registry, //
                       PrintStream output, //
                       String prefix, //
                       Locale locale, //
                       Clock clock, //
                       TimeZone timeZone, //
                       TimeUnit rateUnit, //
                       TimeUnit durationUnit, //
                       MetricFilter filter, //
                       Set<MetricAttribute> disabledMetricAttributes) {
    this.registry = registry;
    this.output = output;
    this.prefix = prefix;
    this.locale = locale;
    this.clock = clock;
    this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
    this.dateFormat.setTimeZone(timeZone);
    this.rateFactor = rateUnit.toSeconds(1);
    this.rateUnit = calculateRateUnit(rateUnit);
    this.durationFactor = durationUnit.toNanos(1);
    this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
    this.filter = filter;
    this.disabledMetricAttributes = disabledMetricAttributes != null ? disabledMetricAttributes : Collections
        .emptySet();
}
 
Example 2
Source File: RareManager.java    From Kepler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Tick manager for checking expiry of the rare on sale.
 *
 * @param tickTime the global tick counter instance
 * @throws SQLException for when selectNewRare() fails
 */
public void performRareManagerJob(AtomicLong tickTime) throws SQLException {
    // Rare cycle management
    TimeUnit rareManagerUnit = TimeUnit.valueOf(GameConfiguration.getInstance().getString("rare.cycle.refresh.timeunit"));
    long interval = rareManagerUnit.toSeconds(GameConfiguration.getInstance().getInteger("rare.cycle.refresh.interval"));

    RareManager.getInstance().getTick().incrementAndGet();

    // Save tick time every 60 seconds...
    if (tickTime.get() % 60 == 0) {
        RareManager.getInstance().saveTick();
    }

    // Select new rare
    if (RareManager.getInstance().getTick().get() >= interval) {
        RareManager.getInstance().selectNewRare();
    }
}
 
Example 3
Source File: JDBCStorage.java    From Carbonado with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }

    return ps;
}
 
Example 4
Source File: GrpcUtil.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public String toAsciiString(Long timeoutNanos) {
  long cutoff = 100000000;
  TimeUnit unit = TimeUnit.NANOSECONDS;
  if (timeoutNanos < 0) {
    throw new IllegalArgumentException("Timeout too small");
  } else if (timeoutNanos < cutoff) {
    return timeoutNanos + "n";
  } else if (timeoutNanos < cutoff * 1000L) {
    return unit.toMicros(timeoutNanos) + "u";
  } else if (timeoutNanos < cutoff * 1000L * 1000L) {
    return unit.toMillis(timeoutNanos) + "m";
  } else if (timeoutNanos < cutoff * 1000L * 1000L * 1000L) {
    return unit.toSeconds(timeoutNanos) + "S";
  } else if (timeoutNanos < cutoff * 1000L * 1000L * 1000L * 60L) {
    return unit.toMinutes(timeoutNanos) + "M";
  } else {
    return unit.toHours(timeoutNanos) + "H";
  }
}
 
Example 5
Source File: MemcachedClient.java    From ob1k with Apache License 2.0 5 votes vote down vote up
public MemcachedClient(final MemcacheClient<V> folsomClient,
                       final CacheKeyTranslator<K> keyTranslator,
                       final long expiration,
                       final TimeUnit timeUnit,
                       final String cacheName) {
  this.folsomClient = Objects.requireNonNull(folsomClient, "folsomClient must not be null");
  this.keyTranslator = Objects.requireNonNull(keyTranslator, "keyTranslator must not be null");
  this.expirationSeconds = (int) timeUnit.toSeconds(expiration);
  this.cacheName = Objects.requireNonNull(cacheName, "cacheName must not be null");
}
 
Example 6
Source File: ExecutePlanAction.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
static CollectionAdminRequest.RequestStatusResponse waitForTaskToFinish(SolrCloudManager cloudManager, 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 {
      statusResponse = (CollectionAdminRequest.RequestStatusResponse)cloudManager.request(CollectionAdminRequest.requestStatus(requestId));
      state = statusResponse.getRequestStatus();
      if (state == RequestStatusState.COMPLETED || state == RequestStatusState.FAILED) {
        log.trace("Task with requestId={} finished with state={} in {}s", requestId, state, i * 5);
        cloudManager.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);
        cloudManager.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);
      throw e;
    }
    if (i > 0 && i % 5 == 0) {
      log.trace("Task with requestId={} still not complete after {}s. Last state={}", requestId, i * 5, state);
    }
    cloudManager.getTimeSource().sleep(5000);
  }
  log.debug("Task with requestId={} did not complete within {} seconds. Last state={}", timeoutSeconds, requestId, state);
  return statusResponse;
}
 
Example 7
Source File: AccessTimeObjectHolder.java    From triava with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 *   |-------------- maxCacheTimeMillis --------------|
 *   |                                                |
 *   |--- newMaxCacheTimeMillis ---|                  |
 *   |                             |                  |
 *  -|---------|-------------------|------------------|------------------------------------- time
 *   |         |                   |                  |
 *   |         now                 now + delayMillis  |
 *   |                  = expirationOnNewExpireUntil  |
 *   |                                                |
 *   inputDate + baseTimeMillis = creationTime        creationTime + maxCacheTime
 * </pre>
 * 
 * @param maxDelay The maximum delay time until the object will be expired
 * @param timeUnit The time unit for maxDelay
 * @param random The random generator to use
 */
public void setExpireUntil(int maxDelay, TimeUnit timeUnit, Random random)
{
	// -1- Create a random idleTime in the interval [0 ... maxDelay-1]
	long millis = timeUnit.toMillis(maxDelay);
	final long delayMillis;

	if (millis == 0)
	{
           delayMillis = millis;
       }
       // There is no Random.nextLong(), so we need a special handling to not getting integer overruns
       else if (millis <= Integer.MAX_VALUE)
	{
		delayMillis = random.nextInt((int)millis);
	}
	else
	{
		int maxDelaySecs = (int)timeUnit.toSeconds(maxDelay);
		delayMillis = 1000l * random.nextInt(maxDelaySecs);			
	}

	// -2- Calculate current expiration from cache time and the one from the newly planned expireUntil  
	long maxCacheTimeMillis = SecondsOrMillis.fromInternalToMillis(maxCacheTime);
	long creationTime = getCreationTime();
	long expirationOnCacheTime = maxCacheTimeMillis + creationTime;
	long expirationOnNewExpireUntil = currentTimeMillisEstimate() + delayMillis;
	
	if (maxCacheTimeMillis == 0 || expirationOnNewExpireUntil < expirationOnCacheTime)
	{
		// holder.maxCacheTime was not set (never expires), or new value is smaller => use it
		long newMaxCacheTimeMillis = expirationOnNewExpireUntil - creationTime;
		maxCacheTime = SecondsOrMillis.fromMillisToInternal(newMaxCacheTimeMillis);
	}
	// else: Keep delay, as holder will already expire sooner than delaySecs.
}
 
Example 8
Source File: TimeUtil.java    From UHC with MIT License 5 votes vote down vote up
public static String secondsToString(long toConvert) {
    long seconds = toConvert;
    final TimeUnit[] units = TimeUnit.values();

    final StringBuilder builder = new StringBuilder();

    boolean negative = false;
    if (seconds < 0) {
        negative = true;
        seconds *= -1;
    }

    for (int i = TimeUnit.DAYS.ordinal(); i >= TimeUnit.SECONDS.ordinal(); i--) {
        final TimeUnit unit = units[i];

        final long count = unit.convert(seconds, TimeUnit.SECONDS);

        if (count > 0) {
            builder.append(FORMATTER.format(count))
                    .append(unit.name().toLowerCase().charAt(0))
                    .append(" ");
            seconds -= unit.toSeconds(count);
        }
    }

    if (builder.length() == 0) {
        return "00s";
    }

    builder.setLength(builder.length() - 1);
    String built = builder.toString();

    if (negative) {
        built = "-" + built;
    }

    return built;
}
 
Example 9
Source File: MetricsModule.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
private TimerSerializer(TimeUnit rateUnit, TimeUnit durationUnit,
                        boolean showSamples) {
    super(Timer.class);
    this.rateUnit = calculateRateUnit(rateUnit, "calls");
    this.rateFactor = rateUnit.toSeconds(1);
    this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
    this.durationFactor = 1.0 / durationUnit.toNanos(1);
    this.showSamples = showSamples;
}
 
Example 10
Source File: ScheduledReporter.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ScheduledReporter} instance.
 *
 * @param registry the {@link io.dropwizard.metrics.MetricRegistry} containing the metrics this
 *                 reporter will report
 * @param filter   the filter for which metrics to report
 * @param rateUnit the rate unit
 * @param durationUnit the duration unit
 * @param executor the executor to use while scheduling reporting of metrics.
 */
protected ScheduledReporter(MetricRegistry registry,
                            MetricFilter filter,
                            TimeUnit rateUnit,
                            TimeUnit durationUnit,
                            ScheduledExecutorService executor) {
    this.registry = registry;
    this.filter = filter;
    this.executor = executor;
    this.rateFactor = rateUnit.toSeconds(1);
    this.rateUnit = calculateRateUnit(rateUnit);
    this.durationFactor = 1.0 / durationUnit.toNanos(1);
    this.durationUnit = durationUnit.toString().toLowerCase(Locale.US);
}
 
Example 11
Source File: AudioManager.java    From AudioManagerSDK with Apache License 2.0 5 votes vote down vote up
public Builder maxRecordTime(long timeout, TimeUnit unit) {//设置后会调用监听
    if (timeout < 0) throw new IllegalArgumentException("timeout < 0");
    if (unit == null) throw new IllegalArgumentException("unit == null");
    long seconds = unit.toSeconds(timeout);
    if (seconds > Integer.MAX_VALUE)
        throw new IllegalArgumentException("Timeout too large.");
    if (seconds == 0 && timeout > 0)
        throw new IllegalArgumentException("Timeout too small.");
    this.mMaxRecordTime = (int) seconds;
    return this;
}
 
Example 12
Source File: Helper.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
private static void populateMetered(JsonObject json, Metered meter, TimeUnit rateUnit) {
  double factor = rateUnit.toSeconds(1);
  json.put("count", meter.getCount());
  json.put("meanRate", meter.getMeanRate() * factor);
  json.put("oneMinuteRate", meter.getOneMinuteRate() * factor);
  json.put("fiveMinuteRate", meter.getFiveMinuteRate() * factor);
  json.put("fifteenMinuteRate", meter.getFifteenMinuteRate() * factor);
  String rate = "events/" + rateUnit.toString().toLowerCase();
  json.put("rate", rate);
}
 
Example 13
Source File: VideoListAdapter.java    From android-player-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given duration into a time span string.
 *
 * @param duration elapsed time as number of milliseconds.
 * @return the formatted time span string.
 */
@NonNull
private 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(Locale.getDefault(),"%02d:", hours));
    }

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

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

    return builder.toString();
}
 
Example 14
Source File: JmxReporter.java    From metrics with Apache License 2.0 4 votes vote down vote up
private JmxMeter(Metered metric, ObjectName objectName, TimeUnit rateUnit) {
    super(objectName);
    this.metric = metric;
    this.rateFactor = rateUnit.toSeconds(1);
    this.rateUnit = ("events/" + calculateRateUnit(rateUnit)).intern();
}
 
Example 15
Source File: ZigbeeConfigContext.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void offlineTimeout(long timeout, TimeUnit unit) {
   long secs = unit.toSeconds(timeout);
   if (timeout != 0 && secs == 0) secs = 1;
   offlineTimeout(secs);
}
 
Example 16
Source File: JobTrigger.java    From actframework with Apache License 2.0 4 votes vote down vote up
static JobTrigger fixedDelay(long interval, TimeUnit timeUnit, boolean startImmediately) {
    return new _FixedDelay(timeUnit.toSeconds(interval), startImmediately);
}
 
Example 17
Source File: AdvertisingPacketUtil.java    From BLE-Indoor-Positioning with Apache License 2.0 4 votes vote down vote up
public static float getPacketFrequency(int packetCount, long duration, TimeUnit timeUnit) {
    if (duration == 0) {
        return 0;
    }
    return packetCount / (float) (timeUnit.toSeconds(duration));
}
 
Example 18
Source File: MetricsElasticsearchModule.java    From oneops with Apache License 2.0 4 votes vote down vote up
public MeterSerializer(TimeUnit rateUnit, String timestampFieldname) {
    super(JsonMeter.class);
    this.timestampFieldname = timestampFieldname;
    this.rateFactor = rateUnit.toSeconds(1);
    this.rateUnit = calculateRateUnit(rateUnit, "events");
}
 
Example 19
Source File: RetrofitCache.java    From RetrofitCache with MIT License 4 votes vote down vote up
public CacheConfig getCacheTime(String url){
    CacheConfig cacheConfig = new CacheConfig();
    if (mUrlMap!=null){
        CacheConfig config = mUrlMap.get(url);
        if (config!=null){
            return config;
        }
    }
    for (Map serviceMethodCache:mVector) {

        for (Object entry:serviceMethodCache.keySet()){
            Object o = serviceMethodCache.get(entry);
            try {

                if (mUrlAragsMap.containsKey(url)){
                    Object[] args = (Object[]) mUrlAragsMap.get(url);
                    String reqUrl =  buildRequestUrl(o,args);
                    if (reqUrl.equals(url)){
                        Method m = (Method) entry;
                        Cache cache =  m.getAnnotation(Cache.class);
                        if (cache!=null){
                            TimeUnit timeUnit =  mDefaultTimeUnit;
                            if (cache.timeUnit() != TimeUnit.NANOSECONDS){
                                timeUnit = cache.timeUnit();
                            }
                            long t = mDefaultTime;
                            if (cache.time() != -1){
                                t = cache.time();
                            }
                            long tm =  timeUnit.toSeconds(t);
                            cacheConfig.setTime(tm);
                            cacheConfig.setForceCacheNoNet(cache.forceCacheNoNet());
                            getUrlMap().put(url, cacheConfig);
                            return cacheConfig;
                        }else{
                            getUrlMap().put(url, cacheConfig);
                            return cacheConfig;
                        }
                    }
                }
            } catch (Exception e) {
                LogUtil.l(e);
            }
        }
    }
    getUrlMap().put(url, cacheConfig);
    return cacheConfig;
}
 
Example 20
Source File: PeriodicScheduler.java    From org.openntf.domino with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new periodic scheduler
 * 
 * @param start
 *            the next possible start time
 * @param period
 *            If positive: the period, if negative: the delay, if zero: not periodic
 * @param timeUnit
 *            the timeUnit of start & period
 */
public PeriodicScheduler(final long delay, final long period, final TimeUnit timeUnit) {
	super();
	this.nextExecTime.setTimeInMillis(System.currentTimeMillis() + timeUnit.toMillis(delay));
	this.periodSecond = (int) timeUnit.toSeconds(period);
}