List of usage examples for java.util.concurrent TimeUnit MINUTES
TimeUnit MINUTES
To view the source code for java.util.concurrent TimeUnit MINUTES.
Click Source Link
From source file:edu.gmu.isa681.server.core.SessionHandler.java
@Override public void run() { try {//from ww w. jav a 2 s .c o m log.info("Handling request from " + sslSocket.getInetAddress().toString()); currentState = State.NOT_LOGGED_IN; // setup the encoder chnl = new EncodedChannel(sslSocket.getInetAddress().toString(), sslSocket.getInputStream(), DEFAULT_INBOUND_CAPACITY, sslSocket.getOutputStream(), DEFAULT_OUTBOUND_CAPACITY); // setup the exception handler chnl.addExceptionListener(new ChannelExceptionListener() { @Override public void exceptionOccurred(Throwable ex) { handleException(ex); } }); int timeout = CONNECTION_TIMEOUT1; // should login within 1 minute of opening the connection // read and handle requests (with timeout) while (!isShuttingDown()) { Encodeable request = chnl.read(timeout, TimeUnit.MINUTES); timeout = CONNECTION_TIMEOUT2; // timeout for requests after successful login try { handleRequest(request); } catch (UnexpectedTypeException ex) { handleException(ex); } } } catch (Exception ex) { handleException(ex); } }
From source file:gr.cti.android.experimentation.service.ModelService.java
public String durationString(long millis) { long days = TimeUnit.MILLISECONDS.toDays(millis); millis -= TimeUnit.DAYS.toMillis(days); 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); return String.valueOf(days) + " Days " + hours + " Hours " + minutes + " Minutes " + seconds + " Seconds"; }
From source file:hudson.cli.CLITest.java
License:asdf
@Issue("JENKINS-41745") @Test/*from w w w . ja v a2s . co m*/ public void interrupt() throws Exception { home = tempHome(); grabCliJar(); r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy( new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin")); SSHD.get().setPort(0); File privkey = tmp.newFile("id_rsa"); FileUtils.copyURLToFile(CLITest.class.getResource("id_rsa"), privkey); User.get("admin") .addProperty(new UserPropertyImpl(IOUtils.toString(CLITest.class.getResource("id_rsa.pub")))); FreeStyleProject p = r.createFreeStyleProject("p"); p.getBuildersList().add(new SleepBuilder(TimeUnit.MINUTES.toMillis(5))); doInterrupt(p, "-remoting", "-i", privkey.getAbsolutePath()); doInterrupt(p, "-ssh", "-user", "admin", "-i", privkey.getAbsolutePath()); doInterrupt(p, "-http", "-auth", "admin:admin"); }
From source file:fr.immotronic.ubikit.pems.modbus.item.RawSlaveProxy.java
@Override public void updateConfiguration(JSONObject configuration) { stopAutomaticReading();// www. j av a 2s .c o m automaticReadingFrequencyInMinutes = 0; if (configuration == null) { this.configuration = null; return; } if (configuration.has(Configuration.AUTO_READING.toString())) { try { JSONArray autoReadings = configuration.getJSONArray(Configuration.AUTO_READING.toString()); for (int i = 0; i < autoReadings.length(); i++) { Collection<ModbusRequest> requests = new ArrayList<ModbusRequest>(); JSONObject reading = autoReadings.getJSONObject(i); int frequency = reading.getInt(Configuration.FREQUENCY.toString()); boolean onClockTick = reading.getBoolean(Configuration.ON_CLOCK_TICK.toString()); JSONArray transactions = reading.getJSONArray(Configuration.TRANSACTIONS.toString()); for (int j = 0; j < transactions.length(); j++) { JSONObject t = transactions.getJSONObject(j); DataType dataType = DataType .valueOf(t.getString(Configuration.TRANSACTIONS_TYPE.toString())); int startingAddress = t.getInt(Configuration.TRANSACTIONS_START_ADDR.toString()); int quantity = t.getInt(Configuration.TRANSACTIONS_QUANTITY.toString()); ModbusRequest request = ModbusRequestImpl.createReadRequest(this, bridge, dataType, startingAddress, quantity); requests.add(request); } if (!requests.isEmpty()) { if (automaticReadingFrequencyInMinutes == 0) { automaticReadingFrequencyInMinutes = frequency; } else { automaticReadingFrequencyInMinutes = -1; } startAutomaticReading(requests, TimeUnit.SECONDS.convert(frequency, TimeUnit.MINUTES), onClockTick); } } } catch (JSONException e) { Logger.warn(LC.gi(), this, "updateConfiguration(): Transmitted JSONObject contains invalid data."); stopAutomaticReading(); return; } catch (IllegalArgumentException e) { Logger.warn(LC.gi(), this, "updateConfiguration(): An invalid Type as been set for an automatic transaction."); Logger.debug(LC.gi(), this, configuration.toString()); stopAutomaticReading(); return; } } this.configuration = configuration; }
From source file:net.sourceforge.fullsync.cli.Main.java
public static void startup(String[] args, Launcher launcher) throws Exception { initOptions();/*from ww w. j a v a 2s .co m*/ String configDir = getConfigDir(); CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); printHelp(); System.exit(1); } if (line.hasOption('V')) { System.out.println(String.format("FullSync version %s", Util.getFullSyncVersion())); //$NON-NLS-1$ System.exit(0); } // Apply modifying options if (!line.hasOption("v")) { //$NON-NLS-1$ System.setErr(new PrintStream(new FileOutputStream(getLogFileName()))); } if (line.hasOption("h")) { //$NON-NLS-1$ printHelp(); System.exit(0); } upgradeLegacyPreferencesLocation(configDir); String profilesFile; if (line.hasOption("P")) { //$NON-NLS-1$ profilesFile = line.getOptionValue("P"); //$NON-NLS-1$ } else { profilesFile = configDir + FullSync.PROFILES_XML; upgradeLegacyProfilesXmlLocation(profilesFile); } final String prefrencesFile = configDir + FullSync.PREFERENCES_PROPERTIES; final Injector injector = Guice.createInjector(new FullSyncModule(line, prefrencesFile)); final RuntimeConfiguration rtConfig = injector.getInstance(RuntimeConfiguration.class); injector.getInstance(ProfileManager.class).setProfilesFileName(profilesFile); final ScheduledExecutorService scheduledExecutorService = injector .getInstance(ScheduledExecutorService.class); final EventListener deadEventListener = new EventListener() { private final Logger logger = LoggerFactory.getLogger("DeadEventLogger"); //$NON-NLS-1$ @Subscribe private void onDeadEvent(DeadEvent deadEvent) { if (!(deadEvent.getEvent() instanceof ShutdownEvent)) { logger.warn("Dead event triggered: {}", deadEvent); //$NON-NLS-1$ } } }; final EventBus eventBus = injector.getInstance(EventBus.class); eventBus.register(deadEventListener); final Semaphore sem = new Semaphore(0); Runtime.getRuntime().addShutdownHook(new Thread(() -> { Logger logger = LoggerFactory.getLogger(Main.class); logger.debug("shutdown hook called, starting orderly shutdown"); //$NON-NLS-1$ eventBus.post(new ShutdownEvent()); scheduledExecutorService.shutdown(); try { scheduledExecutorService.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { // not relevant } logger.debug("shutdown hook finished, releaseing main thread semaphore"); //$NON-NLS-1$ sem.release(); })); if (rtConfig.isDaemon().orElse(false).booleanValue() || rtConfig.getProfileToRun().isPresent()) { finishStartup(injector); sem.acquireUninterruptibly(); System.exit(0); } else { launcher.launchGui(injector); System.exit(0); } }
From source file:ai.grakn.engine.tasks.manager.multiqueue.MultiQueueTaskRunner.java
/** * Stop the main loop, causing run() to exit. * * noThrow() functions used here so that if an error occurs during execution of a * certain step, the subsequent stops continue to execute. *//* w w w . j av a2s . c om*/ public void close() { // Stop execution of kafka consumer noThrow(consumer::wakeup, "Could not wake up task runner thread."); // Wait for the shutdown latch to complete noThrow(shutdownLatch::await, "Error waiting for TaskRunner consumer to exit"); // Interrupt all currently running threads - these will be re-allocated to another Engine. noThrow(executor::shutdown, "Could not shutdown TaskRunner executor."); noThrow(() -> executor.awaitTermination(1, TimeUnit.MINUTES), "Error waiting for TaskRunner executor to shutdown."); LOG.debug("TaskRunner stopped"); }
From source file:com.virtusa.isq.vtaf.report.reporter.ReportBuilder.java
/** * Sets the execution summary.//from w ww . ja v a 2 s . c o m */ public final void setExecutionSummary() { for (TestSuite ts : testExecution.getTestSuites()) { for (TestCase tc : ts.getTestCases()) { int tcId = tc.getTestCaseId(); if (!reportedTestCases.contains(tcId)) { reportedTestCases.add(tcId); if ("Failed".equals(tc.getResult())) { testExecution.setTotalfailedcount(1); testExecution.setTotalerrorcount(1); } else if ("Success".equals(tc.getResult())) { testExecution.setTotalsuccesscount(1); } } } } long millisTotal = stopWatch.getTime(); String hmsEx = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millisTotal), TimeUnit.MILLISECONDS.toMinutes(millisTotal) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisTotal)), TimeUnit.MILLISECONDS.toSeconds(millisTotal) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisTotal))); System.out.println(hmsEx); testExecution.setTotaltime(hmsEx + " HH:MM:SS"); System.out.println("Report created successfully to the folder " + getReportFolderLocation()); long timeTsEnd = System.currentTimeMillis(); long tsTime = timeTsEnd - timeStart; String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(tsTime), TimeUnit.MILLISECONDS.toMinutes(tsTime) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(tsTime)), TimeUnit.MILLISECONDS.toSeconds(tsTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(tsTime))); System.out.println("Time for TestSuite : " + hms); testSuite.setTotaltime(hms); }
From source file:com.epam.catgenome.manager.DownloadFileManager.java
private long getMaxFileDownloadTimeSec() { return TimeUnit.MINUTES.toMillis(maxFileDownloadTimeMin); }
From source file:com.atinternet.tracker.Tool.java
/** * Get minutes count between two millis time * * @param latestTimeMillis long/*from www. j a va 2 s. c o m*/ * @param oldestTimeMillis long * @return int */ static int getMinutesBetweenTimes(long latestTimeMillis, long oldestTimeMillis) { return (int) TimeUnit.MINUTES.convert((latestTimeMillis - oldestTimeMillis), TimeUnit.MILLISECONDS); }
From source file:io.anserini.IndexerCW09B.java
public int indexWithThreads(int numThreads) throws IOException, InterruptedException { System.out.println(//from w w w. j a va 2 s .c om "Indexing with " + numThreads + " threads to directory '" + indexPath.toAbsolutePath() + "'..."); final Directory dir = FSDirectory.open(indexPath); final IndexWriterConfig iwc = new IndexWriterConfig(analyzer()); iwc.setSimilarity(new BM25Similarity()); iwc.setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE); iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); iwc.setRAMBufferSizeMB(256.0); iwc.setUseCompoundFile(false); iwc.setMergeScheduler(new ConcurrentMergeScheduler()); final IndexWriter writer = new IndexWriter(dir, iwc); final ExecutorService executor = Executors.newFixedThreadPool(numThreads); for (Path f : discoverWarcFiles(docDir)) executor.execute(new IndexerThread(writer, f)); //add some delay to let some threads spawn by scheduler Thread.sleep(30000); executor.shutdown(); // Disable new tasks from being submitted try { // Wait for existing tasks to terminate while (!executor.awaitTermination(5, TimeUnit.MINUTES)) { Thread.sleep(1000); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } int numIndexed = writer.maxDoc(); try { writer.commit(); } finally { writer.close(); } return numIndexed; }