List of usage examples for java.util Timer cancel
public void cancel()
From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java
public void close() { closed = true;/*ww w.j a v a 2s.co m*/ Timer pingTimer = this.pingTimer; if (pingTimer != null) { pingTimer.cancel(); } clearPongTimeoutTimer(); Session session = this.session; this.session = null; if (session != null) { try { session.close(); } catch (Exception e) { logger.debug("Closing sessing failed {}", e); } } try { webSocketClient.stop(); } catch (InterruptedException e) { // Just ignore } catch (Exception e) { logger.debug("Stopping websocket failed {}", e); } webSocketClient.destroy(); }
From source file:org.jbpm.msg.jms.AsyncProcessingTest.java
private void processAllJobs(final long maxWait) { boolean jobsAvailable = true; // install a timer that will interrupt if it takes too long // if that happens, it will lead to an interrupted exception and the test will fail TimerTask interruptTask = new TimerTask() { Thread testThread = Thread.currentThread(); public void run() { log.debug("test " + getName() + " took too long. going to interrupt..."); testThread.interrupt();/*from w ww. j ava2 s . co m*/ } }; Timer timer = new Timer(); timer.schedule(interruptTask, maxWait); try { while (jobsAvailable) { log.debug("going to sleep for 200 millis, waiting for the job executor to process more jobs"); Thread.sleep(200); jobsAvailable = areJobsAvailable(); } } catch (InterruptedException e) { fail("test execution exceeded treshold of " + maxWait + " milliseconds"); } finally { timer.cancel(); } }
From source file:org.camunda.bpm.example.spring.servlet.pa.ArquillianTest.java
public void waitForJobExecutorToProcessAllJobs(JobExecutor jobExecutor, long maxMillisToWait) { int checkInterval = 1000; jobExecutor.start();/*from w ww . jav a2 s .c o m*/ try { Timer timer = new Timer(); InteruptTask task = new InteruptTask(Thread.currentThread()); timer.schedule(task, maxMillisToWait); boolean areJobsAvailable = true; try { while (areJobsAvailable && !task.isTimeLimitExceeded()) { Thread.sleep(checkInterval); areJobsAvailable = areJobsAvailable(); } } catch (InterruptedException e) { } finally { timer.cancel(); } if (areJobsAvailable) { throw new ProcessEngineException("time limit of " + maxMillisToWait + " was exceeded"); } } finally { jobExecutor.shutdown(); } }
From source file:org.openhab.persistence.rrd4j.internal.RRD4jService.java
/** * @{inheritDoc}// www. j a v a 2 s .c o m */ public synchronized void store(final Item item, final String alias) { final String name = alias == null ? item.getName() : alias; RrdDb db = getDB(name); if (db != null) { ConsolFun function = getConsolidationFunction(db); long now = System.currentTimeMillis() / 1000; if (function != ConsolFun.AVERAGE) { try { // we store the last value again, so that the value change in the database is not interpolated, but // happens right at this spot if (now - 1 > db.getLastUpdateTime()) { // only do it if there is not already a value double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE); if (!Double.isNaN(lastValue)) { Sample sample = db.createSample(); sample.setTime(now - 1); sample.setValue(DATASOURCE_STATE, lastValue); sample.update(); logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name, mapToState(lastValue, item.getName())); } } } catch (IOException e) { logger.debug("Error storing last value (again): {}", e.getMessage()); } } try { Sample sample = db.createSample(); sample.setTime(now); DecimalType state = (DecimalType) item.getStateAs(DecimalType.class); if (state != null) { double value = state.toBigDecimal().doubleValue(); if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be adjusted by stepsize value = value * db.getRrdDef().getStep(); } sample.setValue(DATASOURCE_STATE, value); sample.update(); logger.debug("Stored '{}' with state '{}' in rrd4j database", name, state); } } catch (IllegalArgumentException e) { if (e.getMessage().contains("at least one second step is required")) { // we try to store the value one second later TimerTask task = new TimerTask() { public void run() { store(item, name); } }; Timer timer = timers.get(name); if (timer != null) { timer.cancel(); timers.remove(name); } timer = new Timer(); timers.put(name, timer); timer.schedule(task, 1000); } else { logger.warn("Could not persist '{}' to rrd4j database: {}", new String[] { name, e.getMessage() }); } } catch (Exception e) { logger.warn("Could not persist '{}' to rrd4j database: {}", new String[] { name, e.getMessage() }); } try { db.close(); } catch (IOException e) { logger.debug("Error closing rrd4j database: {}", e.getMessage()); } } }
From source file:de.yaacc.player.AbstractPlayer.java
protected void executeCommand(TimerTask command, Date executionTime) { if (execTimer != null) { execTimer.cancel(); }//from w w w .j a va 2 s .c o m Timer execTimer = new Timer(); execTimer.schedule(command, executionTime); }
From source file:dk.netarkivet.common.utils.ProcessUtils.java
/** Wait for the end of a process, but only for a limited time. This * method takes care of the ways waitFor can get interrupted. * * @param p Process to wait for//w ww . j a v a2 s .c o m * @param maxWait The maximum number of milliseconds to wait for the * process to exit. * @return Exit value for process, or null if the process didn't exit * within the expected time. */ public static Integer waitFor(final Process p, long maxWait) { ArgumentNotValid.checkNotNull(p, "Process p"); ArgumentNotValid.checkPositive(maxWait, "long maxWait"); long startTime = System.currentTimeMillis(); Timer timer = new Timer(true); final Thread waitThread = Thread.currentThread(); boolean wakeupScheduled = false; final AtomicBoolean doneWaiting = new AtomicBoolean(false); while (System.currentTimeMillis() < startTime + maxWait) { try { if (!wakeupScheduled) { // First time in here, we need to start the wakup thread, // but be sure it doesn't notify us too early or too late. synchronized (waitThread) { timer.schedule(new TimerTask() { public void run() { synchronized (waitThread) { if (!doneWaiting.get()) { waitThread.interrupt(); } } } }, maxWait); wakeupScheduled = true; } } p.waitFor(); break; } catch (InterruptedException e) { // May happen for a number of reasons. We just check if we've // timed out yet when we go through the loop again. } } synchronized (waitThread) { timer.cancel(); doneWaiting.set(true); Thread.interrupted(); // In case the timer task interrupted. } try { return p.exitValue(); } catch (IllegalThreadStateException e) { log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime) + " milliseconds"); return null; } }
From source file:im.vector.receiver.VectorUniversalLinkReceiver.java
/** * Start the universal link management when the login process is done. * If there is no active activity, launch the home activity * * @param aContext the context.//ww w. j a v a 2 s. c o m */ private void manageRoomOnActivity(final Context aContext) { final Activity currentActivity = VectorApp.getCurrentActivity(); if (null != currentActivity) { currentActivity.runOnUiThread(new Runnable() { @Override public void run() { manageRoom(aContext); } }); } else { // clear the activity stack to home activity Intent intent = new Intent(aContext, VectorHomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(VectorHomeActivity.EXTRA_WAITING_VIEW_STATUS, VectorHomeActivity.WAITING_VIEW_START); aContext.startActivity(intent); try { final Timer wakeup = new Timer(); wakeup.schedule(new TimerTask() { @Override public void run() { wakeup.cancel(); manageRoomOnActivity(aContext); } }, 200); } catch (Throwable throwable) { Log.e(LOG_TAG, "## manageRoomOnActivity timer creation failed " + throwable.getMessage()); manageRoomOnActivity(aContext); } } }
From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java
void clearPongTimeoutTimer() { Timer pongTimeoutTimer = this.pongTimeoutTimer; this.pongTimeoutTimer = null; if (pongTimeoutTimer != null) { pongTimeoutTimer.cancel(); }//from w w w .j av a 2s . co m }
From source file:org.gw4e.eclipse.facade.GraphWalkerFacade.java
public static List<IFile> generateOffLineFromFile1(IWorkbenchWindow ww, TestResourceGeneration dcp, BuildPolicy[] generators, int timeout, IProgressMonitor monitor) throws IOException, CoreException, InterruptedException { IFile graphModel = dcp.getGraphIFile(); List<IFile> ret = new ArrayList<IFile>(); List<Context> executionContexts = new ArrayList<Context>(); for (BuildPolicy policy : generators) { String startElement = getStartElement(dcp.getGraphFile()); Path path = dcp.getInputPath(); String generator = policy.getPathGenerator(); String msg = "Offline arguments: " + path + " " + generator + " " + startElement; ResourceManager.logInfo(graphModel.getProject().getName(), msg); addContexts(executionContexts, path, generator, startElement); }//from w w w . java2s. c o m int index = 0; for (Context context : executionContexts) { OfflineContext oc = new OfflineContext(generators[index]); index++; dcp.addOfflineContext(oc); TestExecutor executor = new TestExecutor(context); executor.getMachine().addObserver(new Observer() { @Override public void update(Machine machine, Element element, EventType type) { if (EventType.BEFORE_ELEMENT.equals(type)) { oc.addMethodName(element.getName()); if (monitor.isCanceled()) { throw new RuntimeException( new InterruptedException(MessageUtil.getString("timeoutofflineorcancelled"))); } } } }); Timer canceller = new Timer(); canceller.schedule(new TimerTask() { @Override public void run() { try { monitor.setCanceled(true); } catch (Throwable e) { } } }, timeout * 1000); try { Result result = executor.execute(); canceller.cancel(); } catch (TestExecutionException e) { String reason = e.getResult().getResultsAsString(); canceller.cancel(); ResourceManager.logException(e, reason); if (!ErrorDialog.AUTOMATED_MODE) { // Avoid displaying a window while running automated mode DialogManager.asyncDisplayErrorMessage(MessageUtil.getString("error"), reason, e); } } catch (Throwable e) { canceller.cancel(); ResourceManager.logException(e); if (!ErrorDialog.AUTOMATED_MODE) { // Avoid displaying a window while running automated mode DialogManager.asyncDisplayErrorMessage(MessageUtil.getString("error"), MessageUtil.getString("an_error_occured_while_running_offline_tool"), e); } return ret; } } dcp.updateWithOfflines(); generateFromFile(ww, dcp, monitor); return ret; }
From source file:ubc.pavlab.aspiredb.server.biomartquery.BioMartQueryServiceImpl.java
private void updateCache() throws BioMartServiceException { /**/*from w w w.jav a2 s. c om*/ * Commented out code to check if cache hasExpired() because it takes ~8-10ms everytime this method is called. * Assuming cache never expires. */ // if ( this.bioMartCache.hasExpired() ) { if (geneCache == null) { Dataset dataset = new Dataset("hsapiens_gene_ensembl"); dataset.Filter.add( new Filter("chromosome_name", "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y")); dataset.Attribute.add(new Attribute("ensembl_gene_id")); dataset.Attribute.add(new Attribute("hgnc_symbol")); dataset.Attribute.add(new Attribute("description")); dataset.Attribute.add(new Attribute("gene_biotype")); dataset.Attribute.add(new Attribute("chromosome_name")); dataset.Attribute.add(new Attribute("start")); dataset.Attribute.add(new Attribute("end")); Query query = new Query(); query.Dataset = dataset; StringWriter xmlQueryWriter = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Query.class, Dataset.class, Filter.class, Attribute.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); xmlQueryWriter = new StringWriter(); jaxbMarshaller.marshal(query, xmlQueryWriter); } catch (JAXBException e) { String errorMessage = "Cannot initialize genes from BioMart"; log.error(errorMessage, e); throw new BioMartServiceException(errorMessage); } final StopWatch timer = new StopWatch(); timer.start(); Timer uploadCheckerTimer = new Timer(true); uploadCheckerTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { log.info("Waiting for BioMart response ... " + timer.getTime() + " ms"); } }, 0, 100 * 1000); String response = sendRequest(xmlQueryWriter.toString()); uploadCheckerTimer.cancel(); String[] rows = StringUtils.split(response, "\n"); Collection<GeneValueObject> genes = new HashSet<GeneValueObject>(); int rowsLength = rows.length; if (rowsLength <= 1) { String errorMessage = "Error: retrieved only " + rowsLength + " row of gene data from BioMart" + (rowsLength == 1 ? "(Error message from BioMart: " + rows[0] + ")" : ""); log.error(errorMessage); throw new BioMartServiceException(errorMessage); } geneCache = new HashMap<>(rowsLength); for (String row : rows) { String[] fields = row.split("\t"); int index = 0; String ensemblId = fields[index++]; String symbol = fields[index++]; String name = fields[index++]; String geneBiotype = fields[index++]; String chromosome = fields[index++]; String start = fields[index++]; String end = fields[index++]; // Ignore results that do not have required attributes. if (ensemblId.equals("") || symbol.equals("") || chromosome.equals("") || start.equals("") || end.equals("")) { continue; } int sourceIndex = name.indexOf(" [Source:"); name = sourceIndex >= 0 ? name.substring(0, sourceIndex) : name; GeneValueObject gene = new GeneValueObject(ensemblId, symbol, name, geneBiotype, "human"); int startBase = Integer.valueOf(start); int endBase = Integer.valueOf(end); if (startBase < endBase) { gene.setGenomicRange(new GenomicRange(chromosome, startBase, endBase)); } else { gene.setGenomicRange(new GenomicRange(chromosome, endBase, startBase)); } // organize genes by bin, this is for performance reasons, see Bug 4210 int bin = gene.getGenomicRange().getBin(); if (!geneCache.containsKey(bin)) { geneCache.put(bin, new HashSet<GeneValueObject>()); } geneCache.get(bin).add(gene); genes.add(gene); } this.bioMartCache.putAll(genes); log.info("BioMart request to (" + BIO_MART_URL + ") took " + timer.getTime() + " ms and loaded " + genes.size() + " genes"); } }