/** * test DST start with offset not fitting interval, e.g. Asia/Kathmandu adding 15min on * 1986-01-01T00:00:00 the interval from 1986-01-01T00:15:00+05:45 to 1986-01-01T00:20:00+05:45 to * only be 5min long */ public void testTimeInterval_Kathmandu_DST_Start() { long interval = TimeUnit.MINUTES.toMillis(20); DateTimeZone tz = DateTimeZone.forID("Asia/Kathmandu"); Rounding rounding = new TimeIntervalRounding(interval, tz); assertThat( rounding.round(time("1985-12-31T23:55:00+05:30")), isDate(time("1985-12-31T23:40:00+05:30"), tz)); assertThat( rounding.round(time("1986-01-01T00:16:00+05:45")), isDate(time("1986-01-01T00:15:00+05:45"), tz)); assertThat( time("1986-01-01T00:15:00+05:45") - time("1985-12-31T23:40:00+05:30"), equalTo(TimeUnit.MINUTES.toMillis(20))); assertThat( rounding.round(time("1986-01-01T00:26:00+05:45")), isDate(time("1986-01-01T00:20:00+05:45"), tz)); assertThat( time("1986-01-01T00:20:00+05:45") - time("1986-01-01T00:15:00+05:45"), equalTo(TimeUnit.MINUTES.toMillis(5))); assertThat( rounding.round(time("1986-01-01T00:46:00+05:45")), isDate(time("1986-01-01T00:40:00+05:45"), tz)); assertThat( time("1986-01-01T00:40:00+05:45") - time("1986-01-01T00:20:00+05:45"), equalTo(TimeUnit.MINUTES.toMillis(20))); }
private String getAvgTimePerTick(SortedMap<Long, Record> records) { long sum = 0; for (Map.Entry<Long, Record> en : records.entrySet()) { sum += en.getValue().getLastCallDiff(); } long globalavg = sum / records.size(); sum = 0; Set<Map.Entry<Long, Record>> subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(15)).entrySet(); for (Map.Entry<Long, Record> en : subset) { sum += en.getValue().getLastCallDiff(); } long min15avg = sum / subset.size(); sum = 0; subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(10)).entrySet(); for (Map.Entry<Long, Record> en : subset) { sum += en.getValue().getLastCallDiff(); } long min10avg = sum / subset.size(); sum = 0; subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)).entrySet(); for (Map.Entry<Long, Record> en : subset) { sum += en.getValue().getLastCallDiff(); } long min5avg = sum / subset.size(); sum = 0; subset = records.tailMap(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1)).entrySet(); for (Map.Entry<Long, Record> en : subset) { sum += en.getValue().getLastCallDiff(); } long min1avg = sum / subset.size(); return globalavg + " " + ChatColor.GRAY + min15avg + " " + ChatColor.YELLOW + min10avg + " " + ChatColor.GOLD + min5avg + " " + ChatColor.GREEN + min1avg; }
// Default config static { config.setMaxTotal(100); config.setMaxTotalPerKey(100); config.setMaxIdlePerKey(100); config.setMinIdlePerKey(100); config.setTestOnBorrow(true); config.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5)); config.setSoftMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5)); config.setJmxEnabled(false); }
private static String formatInterval(final long l) { final long hr = TimeUnit.MILLISECONDS.toHours(l); final long min = TimeUnit.MILLISECONDS.toMinutes(l - TimeUnit.HOURS.toMillis(hr)); final long sec = TimeUnit.MILLISECONDS.toSeconds( l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min)); final long ms = TimeUnit.MILLISECONDS.toMillis( l - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec)); return String.format("%02dh:%02dm:%02d.%03ds", hr, min, sec, ms); }
public SerialMain(CommandLine cmd, MoteList motelist) { this.cmd = cmd; this.motelist = motelist; // get value of time, if not set, use default 15 time = TimeUnit.MINUTES.toMillis(Integer.parseInt(cmd.getOptionValue("T"))); }
/** * Special test for intervals that don't fit evenly into rounding interval. In this case, when * interval crosses DST transition point, rounding in local time can land in a DST gap which * results in wrong UTC rounding values. */ public void testIntervalRounding_NotDivisibleInteval() { DateTimeZone tz = DateTimeZone.forID("CET"); long interval = TimeUnit.MINUTES.toMillis(14); Rounding rounding = new Rounding.TimeIntervalRounding(interval, tz); assertThat( rounding.round(time("2016-03-27T01:41:00+01:00")), isDate(time("2016-03-27T01:30:00+01:00"), tz)); assertThat( rounding.round(time("2016-03-27T01:51:00+01:00")), isDate(time("2016-03-27T01:44:00+01:00"), tz)); assertThat( rounding.round(time("2016-03-27T01:59:00+01:00")), isDate(time("2016-03-27T01:58:00+01:00"), tz)); assertThat( rounding.round(time("2016-03-27T03:05:00+02:00")), isDate(time("2016-03-27T03:00:00+02:00"), tz)); assertThat( rounding.round(time("2016-03-27T03:12:00+02:00")), isDate(time("2016-03-27T03:08:00+02:00"), tz)); assertThat( rounding.round(time("2016-03-27T03:25:00+02:00")), isDate(time("2016-03-27T03:22:00+02:00"), tz)); assertThat( rounding.round(time("2016-03-27T03:39:00+02:00")), isDate(time("2016-03-27T03:36:00+02:00"), tz)); }
/** * test DST end with interval rounding CET: 25 October 2015, 03:00:00 clocks were turned backward * 1 hour to 25 October 2015, 02:00:00 local standard time */ public void testTimeIntervalCET_DST_End() { long interval = TimeUnit.MINUTES.toMillis(20); DateTimeZone tz = DateTimeZone.forID("CET"); Rounding rounding = new TimeIntervalRounding(interval, tz); assertThat( rounding.round(time("2015-10-25T01:55:00+02:00")), isDate(time("2015-10-25T01:40:00+02:00"), tz)); assertThat( rounding.round(time("2015-10-25T02:15:00+02:00")), isDate(time("2015-10-25T02:00:00+02:00"), tz)); assertThat( rounding.round(time("2015-10-25T02:35:00+02:00")), isDate(time("2015-10-25T02:20:00+02:00"), tz)); assertThat( rounding.round(time("2015-10-25T02:55:00+02:00")), isDate(time("2015-10-25T02:40:00+02:00"), tz)); // after DST shift assertThat( rounding.round(time("2015-10-25T02:15:00+01:00")), isDate(time("2015-10-25T02:00:00+01:00"), tz)); assertThat( rounding.round(time("2015-10-25T02:35:00+01:00")), isDate(time("2015-10-25T02:20:00+01:00"), tz)); assertThat( rounding.round(time("2015-10-25T02:55:00+01:00")), isDate(time("2015-10-25T02:40:00+01:00"), tz)); assertThat( rounding.round(time("2015-10-25T03:15:00+01:00")), isDate(time("2015-10-25T03:00:00+01:00"), tz)); }
/** Entry point for a streaming Fizz Buzz! */ public static void main(String[] args) throws Exception { Topology topology = new Topology(); // Declare an infinite stream of Long values TStream<Long> counting = BeaconStreams.longBeacon(topology); // Throttle the rate to allow the output to be seen easier counting = counting.throttle(100, TimeUnit.MILLISECONDS); // Print the tuples to standard output playFizzBuzz(counting).print(); // At this point the streaming topology (streaming) is // declared, but no data is flowing. The topology // must be submitted to a StreamsContext to be executed. // Since this is an streaming graph with an endless // data source it will run for ever Future<?> runningTopology = StreamsContextFactory.getEmbedded().submit(topology); // Run for one minute before canceling. Thread.sleep(TimeUnit.MINUTES.toMillis(1)); runningTopology.cancel(true); }
private void initializeThreads() { int startdelay = (int) (SettingUtil.getSettingDouble("start_delay_seconds") * 20); int savefrequency = SettingUtil.getSettingInt("save_interval_seconds") * 20; if (startdelay <= 0) startdelay = 1; if (savefrequency <= 0) savefrequency = 300; // data getServer() .getScheduler() .scheduleAsyncRepeatingTask( this, new Runnable() { @Override public void run() { DataManager.saveAllData(); } }, startdelay, savefrequency); getServer() .getScheduler() .scheduleAsyncRepeatingTask( this, new AsyncIPMatcherTask(), 50, TimeUnit.MINUTES.toMillis(getConfig().getInt("cache_interval_seconds", 10))); }
/** Created by RETRO on 23/08/2015. */ public class LocationManager { private static final int NUM_UPDATES_INTERVAL = 1; private static final long INTERVAL = TimeUnit.MINUTES.toMillis(5); private static final int LOCATION_TIMEOUT = 2; public static Observable<Location> checkLocation(Context mContext) { ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(mContext); LocationRequest locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setNumUpdates(NUM_UPDATES_INTERVAL) .setInterval(INTERVAL); Observable<Location> locationObservable = locationProvider .getLastKnownLocation() .timeout(LOCATION_TIMEOUT, TimeUnit.SECONDS, Observable.just((Location) null)) .concatWith(locationProvider.getUpdatedLocation(locationRequest)) .distinctUntilChanged() .observeOn(AndroidSchedulers.mainThread()); return locationObservable; } }
@Provides @Singleton @Named(TIMEOUT_NAME) long getTimeoutMillis(@GerritServerConfig final Config cfg) { return ConfigUtil.getTimeUnit( cfg, "receive", null, "timeout", TimeUnit.MINUTES.toMillis(2), TimeUnit.MILLISECONDS); }
/** * Formats time-of-day using FIX UTCTimeOnly format (HH:mm:ss or HH:mm:ss.SSS). For example, * "23:59:59.999". This class is thread safe. */ public final class TimeOfDayParser { private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1); private static final int MILLIS_PER_MINUTE = (int) TimeUnit.MINUTES.toMillis(1); /** @return number of milliseconds since midnight */ public static int parseTimeOfDay(byte[] buffer, int valueOffset, int valueLength) { // HH:mm:ss.SSS // 012345678901 int hours = NumbersParser.parsePositiveInt(buffer, valueOffset + 0, 2); int minutes = NumbersParser.parsePositiveInt(buffer, valueOffset + 3, 2); int seconds = NumbersParser.parsePositiveInt(buffer, valueOffset + 6, 2); int millis = (valueLength > 8) ? NumbersParser.parsePositiveInt(buffer, valueOffset + 9, 3) : 0; if (hours >= 24 || minutes >= 60 || seconds >= 60) throw new FixParserException("Invalid time of day"); return hours * MILLIS_PER_HOUR + minutes * MILLIS_PER_MINUTE + seconds * 1000 + millis; } /** Parses HH:MM:SS into array containing H,M,S elements */ public static int[] parseTimeOfDay(byte[] buffer) { int[] result = new int[3]; result[0] = NumbersParser.parsePositiveInt(buffer, 0, 2); result[1] = NumbersParser.parsePositiveInt(buffer, 3, 2); result[2] = NumbersParser.parsePositiveInt(buffer, 6, 2); if (result[0] >= 24 || result[1] >= 60 || result[2] >= 60) throw new FixParserException("Invalid time of day"); return result; } }
/* * Returns TTL value of ElasticSearch index in milliseconds when TTL * specifier is "ms" / "s" / "m" / "h" / "d" / "w". In case of unknown * specifier TTL is not set. When specifier is not provided it defaults to * days in milliseconds where the number of days is parsed integer from TTL * string provided by user. <p> Elasticsearch supports ttl values being * provided in the format: 1d / 1w / 1ms / 1s / 1h / 1m specify a time unit * like d (days), m (minutes), h (hours), ms (milliseconds) or w (weeks), * milliseconds is used as default unit. * http://www.elasticsearch.org/guide/reference/mapping/ttl-field/. * * @param ttl TTL value provided by user in flume configuration file for the * sink * * @return the ttl value in milliseconds */ private long parseTTL(String ttl) { matcher = matcher.reset(ttl); while (matcher.find()) { if (matcher.group(2).equals("ms")) { return Long.parseLong(matcher.group(1)); } else if (matcher.group(2).equals("s")) { return TimeUnit.SECONDS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("m")) { return TimeUnit.MINUTES.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("h")) { return TimeUnit.HOURS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("d")) { return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("w")) { return TimeUnit.DAYS.toMillis(7 * Integer.parseInt(matcher.group(1))); } else if (matcher.group(2).equals("")) { logger.info("TTL qualifier is empty. Defaulting to day qualifier."); return TimeUnit.DAYS.toMillis(Integer.parseInt(matcher.group(1))); } else { logger.debug("Unknown TTL qualifier provided. Setting TTL to 0."); return 0; } } logger.info("TTL not provided. Skipping the TTL config by returning 0."); return 0; }
@Override public List<Bulletin> findBulletinsForGroupBySource( final String groupId, final int maxPerComponent) { final long fiveMinutesAgo = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5); final ConcurrentMap<String, RingBuffer<Bulletin>> componentMap = bulletinStoreMap.get(groupId); if (componentMap == null) { return Collections.<Bulletin>emptyList(); } final List<Bulletin> allComponentBulletins = new ArrayList<>(); for (final RingBuffer<Bulletin> ringBuffer : componentMap.values()) { allComponentBulletins.addAll( ringBuffer.getSelectedElements( new Filter<Bulletin>() { @Override public boolean select(final Bulletin bulletin) { return bulletin.getTimestamp().getTime() >= fiveMinutesAgo; } }, maxPerComponent)); } return allComponentBulletins; }
private <T extends Source> T waitForSource(String id, Class<T> type) throws InterruptedException, InvalidSyntaxException { T source = null; long timeoutLimit = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5); boolean available = false; while (!available) { if (source == null) { source = serviceManager .getServiceReferences(type, null) .stream() .map(serviceManager::getService) .filter(src -> id.equals(src.getId())) .findFirst() .orElse(null); } if (source != null) { available = source.isAvailable(); } if (!available) { if (System.currentTimeMillis() > timeoutLimit) { fail("Source (" + id + ") was not created in a timely manner."); } Thread.sleep(100); } } LOGGER.info("Source {} is available.", id); return source; }
/** * Creates a new Cluster based on the specified configuration. * * @param stormConf the storm configuration. * @return a new a new {@link Cluster} instance. */ @Override protected Cluster make(Map<String, Object> stormConf) { CassandraConf cassandraConf = new CassandraConf(stormConf); Cluster.Builder cluster = Cluster.builder() .withoutJMXReporting() .withoutMetrics() .addContactPoints(cassandraConf.getNodes()) .withPort(cassandraConf.getPort()) .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE) .withReconnectionPolicy( new ExponentialReconnectionPolicy(100L, TimeUnit.MINUTES.toMillis(1))) .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); final String username = cassandraConf.getUsername(); final String password = cassandraConf.getPassword(); if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { cluster.withAuthProvider(new PlainTextAuthProvider(username, password)); } QueryOptions options = new QueryOptions().setConsistencyLevel(cassandraConf.getConsistencyLevel()); cluster.withQueryOptions(options); return cluster.build(); }
@PostConstruct private void init() { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); client = HttpClients.createDefault(); this.url = telegramUrl + telegramToken + "/sendMessage"; TimerTask timerTask = new TimerTask() { @Override public void run() { SendMessage sendMessage = null; try { if (!outQueue.isEmpty()) { sendMessage = outQueue.take(); deliverMessage(sendMessage); } } catch (InterruptedException e) { logger.error("error in reading outQueue", e); } catch (Exception e) { logger.error("error sending message " + sendMessage, e); } } }; Timer timer = new Timer(); timer.schedule(timerTask, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS.toMillis(200)); }
private Properties getDefaultProperties() { Properties defaultProps = new Properties(); // testing params, DONT TOUCH !!! defaultProps.setProperty("openkad.keyfactory.keysize", "50"); defaultProps.setProperty("openkad.keyfactory.hashalgo", "SHA-256"); defaultProps.setProperty("openkad.bucket.kbuckets.maxsize", "16"); defaultProps.setProperty("openkad.color.nrcolors", "19"); defaultProps.setProperty("openkad.scheme.name", "openkad.udp"); // performance params // handling incoming messages defaultProps.setProperty("openkad.executors.server.nrthreads", "8"); defaultProps.setProperty("openkad.executors.server.max_pending", "512"); // handling registered callback defaultProps.setProperty("openkad.executors.client.nrthreads", "1"); defaultProps.setProperty("openkad.executors.client.max_pending", "20"); // forwarding find node requests defaultProps.setProperty("openkad.executors.forward.nrthreads", "2"); defaultProps.setProperty("openkad.executors.forward.max_pending", "2"); // executing the long find node operations defaultProps.setProperty("openkad.executors.op.nrthreads", "1"); defaultProps.setProperty("openkad.executors.op.max_pending", "2"); // sending back pings defaultProps.setProperty("openkad.executors.ping.nrthreads", "1"); defaultProps.setProperty("openkad.executors.ping.max_pending", "16"); // cache settings defaultProps.setProperty("openkad.cache.validtime", TimeUnit.HOURS.toMillis(10) + ""); defaultProps.setProperty("openkad.cache.size", "100"); defaultProps.setProperty("openkad.cache.share", "1"); // minimum time between successive pings defaultProps.setProperty("openkad.bucket.valid_timespan", TimeUnit.MINUTES.toMillis(1) + ""); // network timeouts and concurrency level defaultProps.setProperty("openkad.net.concurrency", "1"); defaultProps.setProperty("openkad.net.timeout", TimeUnit.SECONDS.toMillis(1000) + ""); defaultProps.setProperty("openkad.net.forwarded.timeout", TimeUnit.SECONDS.toMillis(1200) + ""); defaultProps.setProperty("openkad.color.candidates", "1"); defaultProps.setProperty("openkad.color.slack.size", "1"); defaultProps.setProperty("openkad.color.allcolors", "95"); // interval between successive find node operations for refresh buckets defaultProps.setProperty("openkad.refresh.interval", TimeUnit.SECONDS.toMillis(30000) + ""); // local configuration, please touch defaultProps.setProperty("openkad.net.udp.port", "-1"); defaultProps.setProperty("openkad.local.key", ""); defaultProps.setProperty("openkad.file.nodes.path", "nodes"); // misc defaultProps.setProperty("openkad.seed", "0"); // shani Skademia defaultProps.setProperty("skademlia.siblinglist.size", "8"); defaultProps.setProperty("dht.storage.checkInterval", "" + TimeUnit.SECONDS.toMillis(30000)); return defaultProps; }
private long convertPenaltyToMinutes(long penaltyInMilliseconds) { long penaltyInMinutes = TimeUnit.MILLISECONDS.toMinutes(penaltyInMilliseconds); if (TimeUnit.MINUTES.toMillis(penaltyInMinutes) != penaltyInMilliseconds) { penaltyInMinutes++; } return penaltyInMinutes; }
public void testNonStopManagerLeakTest() throws Throwable { List<WeakReference> weakReferences = new ArrayList<WeakReference>(); for (int i = 0; i < 100; i++) { nonStopManager.begin(TimeUnit.MINUTES.toMillis(10)); try { Collection<NonStopTaskWrapper> collection = nonStopManager.getTimerTasks().values(); Assert.assertEquals(1, collection.size()); NonStopTaskWrapper o = collection.iterator().next(); weakReferences.add(new WeakReference(o.getFuture())); } finally { nonStopManager.finish(); } } { Collection collection = nonStopManager.getTimerTasks().values(); Assert.assertEquals(0, collection.size()); } int gcRefCount = 0; for (long time = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2); System.currentTimeMillis() < time; ) { gcRefCount = 0; System.err.println("Looping for GC"); for (int i = 0; i < 10; i++) { System.gc(); } for (WeakReference ref : weakReferences) { if (ref.get() == null) { gcRefCount++; } } if (gcRefCount > 95) { break; } Thread.sleep(500); } System.err.println("Test passed"); Assert.assertTrue(gcRefCount > 95); }
private ArtifactCache createHttpArtifactCache(BuckEventBus buckEventBus) { URL url; try { url = new URL(getValue("cache", "http_url").or(DEFAULT_HTTP_URL)); } catch (MalformedURLException e) { throw new HumanReadableException(e, "Malformed [cache]http_url: %s", e.getMessage()); } int timeoutSeconds = Integer.parseInt( getValue("cache", "http_timeout_seconds").or(DEFAULT_HTTP_CACHE_TIMEOUT_SECONDS)); boolean doStore = readCacheMode("http_mode", DEFAULT_HTTP_CACHE_MODE); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); final String localhost = getLocalhost(); client .networkInterceptors() .add( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed( chain .request() .newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", localhost) .build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool( new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache( "http", fetchClient, client, url, doStore, projectFilesystem, buckEventBus, Hashing.crc32()); }
public TestSuiteReport waitForSuiteReport( final String user, final String project, final long testSuiteReportId) { return waitForSuiteReport( user, project, testSuiteReportId, TimeUnit.MINUTES.toMillis(120), TimeUnit.SECONDS.toMillis(30)); }
public String getTimeRemaining() { if (state != GameState.STARTED) return state.toString(); /* * Ugh math. */ Long timeLeft = (System.currentTimeMillis() - startTime < TimeUnit.MINUTES.toMillis(5)) ? TimeUnit.MINUTES.toMillis(5) - (System.currentTimeMillis() - startTime) : TimeUnit.MINUTES.toMillis(5) - (System.currentTimeMillis() - startTime); return String.format( "%s %sm %ss.", (System.currentTimeMillis() - startTime < TimeUnit.MINUTES.toMillis(5)) ? "You may join for " : "Game over in ", TimeUnit.MILLISECONDS.toMinutes(timeLeft), TimeUnit.MILLISECONDS.toSeconds(startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeLeft))); }
protected Option[] configurePaxExam() { return options( logLevel(LogLevelOption.LogLevel.WARN), useOwnExamBundlesStartLevel(100), // increase timeout for CI environment systemTimeout(TimeUnit.MINUTES.toMillis(10)), when(Boolean.getBoolean("keepRuntimeFolder")).useOptions(keepRuntimeFolder()), cleanCaches(true)); }
private static String formatDate(long millis) { long hours = TimeUnit.MILLISECONDS.toHours(millis); millis -= TimeUnit.HOURS.toMillis(hours); long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); millis -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); String formatted = String.format("%02d:%02d:%02d", hours, minutes, seconds); // replace heading 00: as it's not accepted by the schema validation return (formatted.replaceFirst("^(00:)+", "")); }
/** * Test that rounded values are always greater or equal to last rounded value if date is * increasing. The example covers an interval around 2011-10-30T02:10:00+01:00, time zone CET, * interval: 2700000ms */ public void testIntervalRoundingMonotonic_CET() { long interval = TimeUnit.MINUTES.toMillis(45); DateTimeZone tz = DateTimeZone.forID("CET"); Rounding rounding = new Rounding.TimeIntervalRounding(interval, tz); List<Tuple<String, String>> expectedDates = new ArrayList<>(); // first date is the date to be rounded, second the expected result expectedDates.add( new Tuple<>("2011-10-30T01:40:00.000+02:00", "2011-10-30T01:30:00.000+02:00")); expectedDates.add( new Tuple<>("2011-10-30T02:02:30.000+02:00", "2011-10-30T01:30:00.000+02:00")); expectedDates.add( new Tuple<>("2011-10-30T02:25:00.000+02:00", "2011-10-30T02:15:00.000+02:00")); expectedDates.add( new Tuple<>("2011-10-30T02:47:30.000+02:00", "2011-10-30T02:15:00.000+02:00")); expectedDates.add( new Tuple<>("2011-10-30T02:10:00.000+01:00", "2011-10-30T02:15:00.000+02:00")); expectedDates.add( new Tuple<>("2011-10-30T02:32:30.000+01:00", "2011-10-30T02:15:00.000+01:00")); expectedDates.add( new Tuple<>("2011-10-30T02:55:00.000+01:00", "2011-10-30T02:15:00.000+01:00")); expectedDates.add( new Tuple<>("2011-10-30T03:17:30.000+01:00", "2011-10-30T03:00:00.000+01:00")); long previousDate = Long.MIN_VALUE; for (Tuple<String, String> dates : expectedDates) { final long roundedDate = rounding.round(time(dates.v1())); assertThat(roundedDate, isDate(time(dates.v2()), tz)); assertThat(roundedDate, greaterThanOrEqualTo(previousDate)); previousDate = roundedDate; } // here's what this means for interval widths assertEquals( TimeUnit.MINUTES.toMillis(45), time("2011-10-30T02:15:00.000+02:00") - time("2011-10-30T01:30:00.000+02:00")); assertEquals( TimeUnit.MINUTES.toMillis(60), time("2011-10-30T02:15:00.000+01:00") - time("2011-10-30T02:15:00.000+02:00")); assertEquals( TimeUnit.MINUTES.toMillis(45), time("2011-10-30T03:00:00.000+01:00") - time("2011-10-30T02:15:00.000+01:00")); }
/** * Check if task should be cached or not. Task should not be cached , only if the task has been * rolled back (Cleared) or failed to be rolled back (ClearedFailed), and been in that status for * several minutes (_cacheTimeInMinutes). * * @param task - Asynchronous task we check to cache or not. * @return - true for uncached object , and false when the object should be cached. */ public synchronized boolean cachingOver(SPMTask task) { // Get time in milliseconds that the task should be cached long SubtractMinutesAsMills = TimeUnit.MINUTES.toMillis(_cacheTimeInMinutes); // check if task has been rolled back (Cleared) or failed to be rolled // back (ClearedFailed) // for SubtractMinutesAsMills of minutes. return (task.getState() == AsyncTaskState.Cleared || task.getState() == AsyncTaskState.ClearFailed) && task.getLastAccessToStatusSinceEnd() < (System.currentTimeMillis() - SubtractMinutesAsMills); }
public static String msecs(long msecs, boolean truncate) { final long hr = TimeUnit.MILLISECONDS.toHours(msecs); msecs -= TimeUnit.HOURS.toMillis(hr); final long min = TimeUnit.MILLISECONDS.toMinutes(msecs); msecs -= TimeUnit.MINUTES.toMillis(min); final long sec = TimeUnit.MILLISECONDS.toSeconds(msecs); msecs -= TimeUnit.SECONDS.toMillis(sec); final long ms = TimeUnit.MILLISECONDS.toMillis(msecs); if (!truncate) return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms); if (hr != 0) return String.format("%2d:%02d:%02d.%03d", hr, min, sec, ms); if (min != 0) return String.format("%2d min %2d.%03d sec", min, sec, ms); return String.format("%2d.%03d sec", sec, ms); }
@Override protected void bindDefaults(Properties properties) { properties.put(TASK_APP_DIRECTORY, "app"); properties.put(TASK_EXECUTOR_BASH_LOG_PATH, "executor.bash.log"); properties.put(TASK_EXECUTOR_JAVA_LOG_PATH, "executor.java.log"); properties.put(TASK_SERVICE_LOG_PATH, "service.log"); properties.put(HARD_KILL_AFTER_MILLIS, Long.toString(TimeUnit.MINUTES.toMillis(3))); properties.put(NUM_CORE_KILL_THREADS, "1"); properties.put(NUM_CORE_THREAD_CHECK_THREADS, "1"); properties.put(CHECK_THREADS_EVERY_MILLIS, Long.toString(TimeUnit.SECONDS.toMillis(5))); properties.put(MAX_TASK_MESSAGE_LENGTH, "80"); properties.put(SHUTDOWN_TIMEOUT_MILLIS, Long.toString(TimeUnit.MINUTES.toMillis(5))); properties.put( IDLE_EXECUTOR_SHUTDOWN_AFTER_MILLIS, Long.toString(TimeUnit.SECONDS.toMillis(30))); properties.put(SHUTDOWN_STOP_DRIVER_AFTER_MILLIS, Long.toString(TimeUnit.SECONDS.toMillis(5))); properties.put(TAIL_LOG_LINES_TO_SAVE, "500"); properties.put(TAIL_LOG_FILENAME, "tail_of_finished_service.log"); properties.put(GLOBAL_TASK_DEFINITION_SUFFIX, ".task.json"); properties.put(LOGROTATE_COMMAND, "logrotate"); properties.put(LOGROTATE_DIRECTORY, "logs"); properties.put(LOGROTATE_MAXAGE_DAYS, "7"); properties.put(LOGROTATE_COUNT, "20"); properties.put(LOGROTATE_DATEFORMAT, "-%Y%m%d%s"); properties.put(LOGROTATE_CONFIG_DIRECTORY, "/etc/logrotate.d"); properties.put(LOGROTATE_STATE_FILE, "logrotate.status"); properties.put(LOGROTATE_EXTRAS_FILES, ""); properties.put(LOGROTATE_EXTRAS_DATEFORMAT, "-%Y%m%d"); properties.put(USE_LOCAL_DOWNLOAD_SERVICE, Boolean.toString(false)); properties.put( LOCAL_DOWNLOAD_SERVICE_TIMEOUT_MILLIS, Long.toString(TimeUnit.MINUTES.toMillis(3))); properties.put(MAX_TASK_THREADS, ""); }
private static void scheduleReminder(Context context, int count) { if (count >= SMSSecurePreferences.getRepeatAlertsCount(context)) { return; } AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION); alarmIntent.putExtra("reminder_count", count); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); long timeout = TimeUnit.MINUTES.toMillis(2); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, pendingIntent); }