List of usage examples for java.util Timer cancel
public void cancel()
From source file:org.jbpm.bpel.persistence.db.AbstractDbTestCase.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/*from w w w. jav a 2 s . c om*/ TimerTask interruptTask = new TimerTask() { Thread testThread = Thread.currentThread(); public void run() { log.debug("test " + getName() + " took too long. going to interrupt..."); testThread.interrupt(); } }; 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(); } jobExecutor.stopAndJoin(); } catch (InterruptedException e) { fail("test execution exceeded treshold of " + maxWait + " milliseconds"); } finally { timer.cancel(); } }
From source file:org.jbpm.db.AbstractDbTestCase.java
private void processAllJobs(final long maxWait, int maxJobs) { 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/*from www . j a va 2s. co m*/ TimerTask interruptTask = new TimerTask() { Thread testThread = Thread.currentThread(); public void run() { log.debug("test " + getName() + " took too long. going to interrupt..."); testThread.interrupt(); } }; 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 = (getNbrOfJobsAvailable() > maxJobs); } jobExecutor.stopAndJoin(); } catch (InterruptedException e) { fail("test execution exceeded treshold of " + maxWait + " milliseconds"); } finally { timer.cancel(); } }
From source file:org.apache.ranger.plugin.service.RangerBasePlugin.java
public void cleanup() { PolicyRefresher refresher = this.refresher; RangerPolicyEngine policyEngine = this.policyEngine; Timer policyEngineRefreshTimer = this.policyEngineRefreshTimer; this.serviceName = null; this.policyEngine = null; this.refresher = null; this.policyEngineRefreshTimer = null; if (refresher != null) { refresher.stopRefresher();// w w w. j a v a2s . co m } if (policyEngineRefreshTimer != null) { policyEngineRefreshTimer.cancel(); } if (policyEngine != null) { policyEngine.cleanup(); } }
From source file:org.apache.hcatalog.hcatmix.load.HCatMapper.java
@Override public void map(LongWritable longWritable, Text text, OutputCollector<LongWritable, IntervalResult> collector, final Reporter reporter) throws IOException { LOG.info(MessageFormat.format("Input: {0}={1}", longWritable, text)); final List<Future<SortedMap<Long, IntervalResult>>> futures = new ArrayList<Future<SortedMap<Long, IntervalResult>>>(); // Initialize tasks List<org.apache.hcatalog.hcatmix.load.tasks.Task> tasks; try {/*from w w w . ja va2 s . com*/ tasks = initializeTasks(jobConf); } catch (Exception e) { throw new RuntimeException(e); } ThreadCreatorTimer createNewThreads = new ThreadCreatorTimer(new TimeKeeper(timeKeeper), tasks, threadIncrementCount, futures, reporter); // Create timer thread to automatically keep on increasing threads at fixed interval Timer newThreadCreator = new Timer(true); newThreadCreator.scheduleAtFixedRate(createNewThreads, 0, threadIncrementIntervalInMillis); // Sleep and let the tasks get expired long remainingTime = timeKeeper.getRemainingTimeIncludingBuffer(); final long sleepPeriod = 2000; for (long i = remainingTime; i > 0; i = i - sleepPeriod) { try { Thread.sleep(sleepPeriod); reporter.progress(); } catch (InterruptedException e) { LOG.error("Got interrupted while sleeping for timer thread to finish"); } } newThreadCreator.cancel(); LOG.info("Time is over, will collect the futures now. Total number of threads: " + futures.size()); SortedMap<Long, IntervalResult> stopWatchAggregatedTimeSeries = new TreeMap<Long, IntervalResult>(); // Merge the corresponding time interval results received from all the threads for each time interval for (TaskExecutor taskExecutor : createNewThreads.getTaskExecutors()) { try { SortedMap<Long, IntervalResult> threadTimeSeries = taskExecutor.getTimeSeriesResult(); for (Map.Entry<Long, IntervalResult> entry : threadTimeSeries.entrySet()) { Long timeStamp = entry.getKey(); IntervalResult intervalResult = entry.getValue(); if (stopWatchAggregatedTimeSeries.containsKey(timeStamp)) { stopWatchAggregatedTimeSeries.get(timeStamp).addIntervalResult(intervalResult); } else { stopWatchAggregatedTimeSeries.put(timeStamp, intervalResult); } LOG.info(MessageFormat.format("{0}: Added {1} stopwatches. Current stopwatch number: {2}", timeStamp, intervalResult.getStopWatchList().size(), stopWatchAggregatedTimeSeries.get(timeStamp).getStopWatchList().size())); } } catch (Exception e) { LOG.error("Error while getting thread results", e); } } // Output the consolidated result for this map along with the number of threads against time LOG.info("Collected all the statistics for #threads: " + createNewThreads.getThreadCount()); SortedMap<Long, Integer> threadCountTimeSeries = createNewThreads.getThreadCountTimeSeries(); int threadCount = 0; for (Map.Entry<Long, IntervalResult> entry : stopWatchAggregatedTimeSeries.entrySet()) { long timeStamp = entry.getKey(); IntervalResult intervalResult = entry.getValue(); if (threadCountTimeSeries.containsKey(timeStamp)) { threadCount = threadCountTimeSeries.get(timeStamp); } intervalResult.setThreadCount(threadCount); collector.collect(new LongWritable(timeStamp), intervalResult); } }
From source file:de.thm.arsnova.services.QuestionService.java
@Override public void cancelDelayedPiRoundChange(final String questionId) { Timer timer = timerList.get(questionId); if (null != timer) { timer.cancel(); timerList.remove(questionId);/*from w w w. ja v a 2s . c om*/ timer.purge(); } }
From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java
@Override public void showText2SpeechAlertDialog() { final AlertDialog dialog = new AlertDialog.Builder(this).setMessage(R.string.alert_tts_message) //.setTitle(R.string.alert_network_title) .setCancelable(true)//ww w. j a va 2 s. co m .setNegativeButton(R.string.alert_tts_btn_settings, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { userInteraction = true; Intent ttsIntent = new Intent(); ttsIntent.setAction(Settings.ACTION_SETTINGS); startActivity(ttsIntent); } }).setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); finishActivity(); userInteraction = true; } }).show(); final Timer t = new Timer(); t.schedule(new TimerTask() { public void run() { if (userInteraction == false) { dialog.dismiss(); // when the task active then close the dialog finishActivity(); } t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report } }, 10000); // after 2 second (or 2000 miliseconds), the task will be active. }
From source file:org.apache.sling.testing.serversetup.jarexec.ShutdownHookSingleProcessDestroyer.java
public void destroyProcess(boolean waitForIt) { Process toDestroy = null;/* w ww. j av a2 s .co m*/ synchronized (this) { toDestroy = process; process = null; } if (toDestroy == null) { return; } toDestroy.destroy(); if (waitForIt) { log.info("Waiting for destroyed process {} to exit (timeout={} seconds)", processInfo, timeoutSeconds); final Thread mainThread = Thread.currentThread(); final Timer t = new Timer(true); final TimerTask task = new TimerTask() { @Override public void run() { mainThread.interrupt(); } }; t.schedule(task, timeoutSeconds * 1000L); try { toDestroy.waitFor(); try { final int exit = toDestroy.exitValue(); log.info("Process {} ended with exit code {}", processInfo, exit); } catch (IllegalStateException ise) { log.error("Failed to destroy process " + processInfo); } } catch (InterruptedException e) { log.error("Timeout waiting for process " + processInfo + " to exit"); } finally { t.cancel(); } } }
From source file:org.mifos.framework.ApplicationInitializer.java
private void cancelMySQLStatement() { // mysql statement cancellation timer (mysql bug 36565) ClassLoader myClassLoader = this.getClass().getClassLoader(); Class clazz;// w ww .jav a2 s. com try { clazz = Class.forName("com.mysql.jdbc.ConnectionImpl", false, myClassLoader); if (!(clazz.getClassLoader() == myClassLoader)) { logger.info("MySQL ConnectionImpl was loaded with another ClassLoader: (" + clazz.getClassLoader() + "): cancelling anyway"); } else { logger.info("MySQL ConnectionImpl was loaded with the WebappClassLoader: cancelling the Timer"); } Field f = clazz.getDeclaredField("cancelTimer"); f.setAccessible(true); Timer timer = (Timer) f.get(null); timer.cancel(); logger.info("completed timer cancellation"); } catch (ClassNotFoundException e) { logger.warn("failed mysql timer cancellation", e); } catch (SecurityException e) { logger.warn("failed mysql timer cancellation", e); } catch (NoSuchFieldException e) { logger.warn("failed mysql timer cancellation", e); } catch (IllegalArgumentException e) { logger.warn("failed mysql timer cancellation", e); } catch (IllegalAccessException e) { logger.warn("failed mysql timer cancellation", e); } catch (NullPointerException e) { logger.info("No mysql timer cancellation required"); // Expected exception, do not log NPE causee } }
From source file:ota.otaupdates.Settings.java
@Override public void onCreate(Bundle savedInstanceState) { if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false)) setTheme(R.style.AppTheme_Light); else/*from w w w .j av a 2 s .c o m*/ setTheme(R.style.AppTheme_Dark); super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); SwitchPreference enable_auto_install = (SwitchPreference) findPreference("enable_auto_install"); if (!Shell.SU.available()) { enable_auto_install.setEnabled(false); enable_auto_install.setChecked(false); enable_auto_install.setSummary(getString(R.string.auto_install_root_only)); } final SwitchPreference setEnglish = (SwitchPreference) findPreference("force_english"); setEnglish.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this); if (MainActivity.sharedPreferences.getBoolean("force_english", false)) builder.setTitle(getString(R.string.force_english_window_title)); else builder.setTitle(getString(R.string.force_default_window_title)); builder.setMessage(getString(R.string.force_english_window_message)); builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }); builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alert = builder.create(); alert.setCancelable(true); alert.show(); return true; } }); SwitchPreference apptheme_light = (SwitchPreference) findPreference("apptheme_light"); apptheme_light.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this); if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false)) setTheme(R.style.AppTheme_Light); else setTheme(R.style.AppTheme_Dark); builder.setMessage(getString(R.string.switch_apptheme_light_window_message)); builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }); builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alert = builder.create(); alert.setCancelable(true); alert.show(); return true; } }); findPreference("clean_junk").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (Build.VERSION.SDK_INT >= 23 && !checkPermission()) { // If user hasn't allowed yet, request the permission. requestPermission(); } final AlertDialog.Builder delete_dialog = new AlertDialog.Builder(Settings.this); delete_dialog.setMessage(R.string.clean_junk_dialog_summary); delete_dialog.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { File folder = new File(Utils.DL_PATH); File fList[] = folder.listFiles(); if (fList != null) { for (i = 0; i < fList.length; i++) { String pes = String.valueOf(fList[i]); if (pes.endsWith(".zip")) { fList[i].delete(); } } } Log.d(getString(R.string.app_name) + ": clean_junk", "Old files cleaned"); Toast.makeText(getApplicationContext(), R.string.clean_junk_toast, Toast.LENGTH_SHORT) .show(); } }); delete_dialog.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); delete_dialog.show(); return true; } }); findPreference("devs").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clickcount++; switch (clickcount) { case 8: case 12: case 16: case 20: case 24: Toast.makeText(getApplicationContext(), R.string.crash_soon, Toast.LENGTH_SHORT).show(); break; case 28: Toast.makeText(getApplicationContext(), R.string.crash_soon_really, Toast.LENGTH_SHORT).show(); final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { clickcount = 0; Toast.makeText(getApplicationContext(), R.string.crash_soon_gaveup, Toast.LENGTH_SHORT).show(); } }); timer.cancel(); } }, 4000, 1); break; case 35: throw new NullPointerException("Well, you pointed at something..."); } return true; } }); }
From source file:org.sonar.server.benchmark.SourceDbBenchmarkTest.java
private void scrollRows() throws SQLException { LOGGER.info("Scroll table FILE_SOURCES"); DbClient dbClient = new DbClient(dbTester.database(), dbTester.myBatis()); Connection connection = dbTester.openConnection(); AtomicLong counter = new AtomicLong(); ProgressTask progress = new ProgressTask(LOGGER, "source file", counter); Timer timer = new Timer("SourceDbScroll"); timer.schedule(progress, ProgressTask.PERIOD_MS, ProgressTask.PERIOD_MS); try {/*w ww .java 2s. c om*/ long start = System.currentTimeMillis(); SourceLineResultSetIterator it = SourceLineResultSetIterator.create(dbClient, connection, 0L); while (it.hasNext()) { SourceLineResultSetIterator.SourceFile row = it.next(); assertThat(row.getLines().size()).isEqualTo(3220); assertThat(row.getFileUuid()).isNotEmpty(); counter.incrementAndGet(); } long end = System.currentTimeMillis(); long period = end - start; long throughputPerSecond = 1000L * counter.get() / period; LOGGER.info(String.format("%d FILE_SOURCES rows scrolled in %d ms (%d rows/second)", counter.get(), period, throughputPerSecond)); } finally { DbUtils.closeQuietly(connection); timer.cancel(); } }