下面列出了java.util.Timer#cancel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void test(String[] args) throws Throwable {
for (int how=0; how<4; how++) {
final CountDownLatch done = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger(0);
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
checkScheduledExecutionTime(this);
count.incrementAndGet();
done.countDown();
}};
scheduleNow(timer, task, how);
done.await();
equal(count.get(), 1);
checkScheduledExecutionTime(task);
if (new java.util.Random().nextBoolean())
sleep(10);
check(task.cancel());
timer.cancel();
checkScheduledExecutionTime(task);
}
}
public static void main(String []s)
{
final Dialog fd = new Dialog(new Frame(), true);
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
System.out.println("RUNNING TASK");
fd.setVisible(false);
fd.dispose();
System.out.println("FINISHING TASK");
}
}, 3000L);
fd.setVisible(true);
t.cancel();
Util.waitForIdle(null);
AbstractTest.pass();
}
void test(String[] args) throws Throwable {
for (int how=0; how<4; how++) {
final CountDownLatch done = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger(0);
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
checkScheduledExecutionTime(this);
count.incrementAndGet();
done.countDown();
}};
scheduleNow(timer, task, how);
done.await();
equal(count.get(), 1);
checkScheduledExecutionTime(task);
if (new java.util.Random().nextBoolean())
sleep(10);
check(task.cancel());
timer.cancel();
checkScheduledExecutionTime(task);
}
}
void test(String[] args) throws Throwable {
for (int how=0; how<4; how++) {
final CountDownLatch done = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger(0);
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
checkScheduledExecutionTime(this);
count.incrementAndGet();
done.countDown();
}};
scheduleNow(timer, task, how);
done.await();
equal(count.get(), 1);
checkScheduledExecutionTime(task);
if (new java.util.Random().nextBoolean())
sleep(10);
check(task.cancel());
timer.cancel();
checkScheduledExecutionTime(task);
}
}
/**
* Enables/disables this motion killer.
* Note: VizPanel uses the value of enabled to build menus, so this method
* should only be changed (indirectly) from there.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
if (enabled) {
timer = new Timer();
timer.scheduleAtFixedRate(this, millis, millis);
} else if (timer != null) {
timer.cancel();
timer = null;
}
}
TimeTest(){
Timer timer = new Timer();
TimerTask task = new TestTask();
thread = Thread.currentThread();
timer.schedule(task, 10000);
run();
timer.cancel();
}
@Override
public void windowDeiconified(WindowEvent e)
{
final int TIME = 200;
final int MILLIS_PER_FRAME = 33;
final float DELTA = MILLIS_PER_FRAME / (float)TIME;
frame.setOpacity(0f);
frame.setState(JFrame.NORMAL);
final Timer timer = new Timer();
TimerTask timerTask = new TimerTask()
{
float opacity = 0f;
@Override
public void run()
{
opacity += DELTA;
if (opacity < 0)
{
frame.setState(JFrame.ICONIFIED);
frame.setOpacity(1f);
timer.cancel();
}
else if (opacity > 1)
{
frame.setOpacity(1f);
timer.cancel();
}
else
{
frame.setOpacity(opacity);
}
}
};
timer.scheduleAtFixedRate(timerTask, MILLIS_PER_FRAME, MILLIS_PER_FRAME);
super.windowDeiconified(e);
}
@NbBundle.Messages("NbDdeBrowserImpl.browser.external=external browser")
@Override
public void run() {
logFine("NbDdeBrowserImpl.run"); // NOI18N
while (true) {
try {
/** url to be displayed */
DisplayTask task = getNextTask();
isDisplaying = true;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (isDisplaying) {
NbDdeBrowserImpl.nativeThread.interrupt();
logFine("interrupted in URLDisplayer.run.TimerTask.run()"); // NOI18N
BrowserUtils.notifyMissingBrowser(Bundle.NbDdeBrowserImpl_browser_external());
}
}
}, /*task.browser.extBrowserFactory.getBrowserStartTimeout() + */ADDITIONAL_WAIT_TIMEOUT);
dispatchURL (task);
timer.cancel();
} catch (InterruptedException ex) {
ExtWebBrowser.getEM().log(Level.INFO, "interrupted in run(): " + ex); // NOI18N
// do nothing
} finally {
isDisplaying = false;
}
}
}
/**
* Shutdown
*/
public void shutdown()
{
if (timers != null)
{
for (Timer t : timers)
{
t.cancel();
t.purge();
}
}
}
public void testOverdueTaskExecutesImmediately() throws Exception {
Timer t = new Timer();
Date date = new Date(System.currentTimeMillis());
t.schedule(new CheckIfExecutedOnTime(null), date);
AtomicBoolean actuallyExecutedOnTime = new AtomicBoolean();
// Scheduled to execute right now but won't do as the other task is sleeping. Check that
// this one executes as soon as the other one finishes.
t.schedule(new CheckIfExecutedOnTime(actuallyExecutedOnTime), date);
// Only the first one sleeps, this will be the two tasks plenty of time to finish.
Thread.sleep(2 * CheckIfExecutedOnTime.SLEEPING_TIME);
t.cancel();
assertTrue(actuallyExecutedOnTime.get());
}
@Test
public void test() throws Exception {
randomlyEnableAutoSoftCommit();
int cnt = random().nextInt(2) + 1;
for (int i = 0; i < cnt; i++) {
createAndDeleteCollection();
}
if (testRestartIntoSafeMode) {
Timer timer = new Timer();
try {
createCollection(DELETE_DATA_DIR_COLLECTION, "conf1", 1, 1, 1);
waitForRecoveriesToFinish(DELETE_DATA_DIR_COLLECTION, false);
jettys.get(0).stop();
// enter safe mode and restart a node
NameNodeAdapter.enterSafeMode(dfsCluster.getNameNode(), false);
int rnd = random().nextInt(10000);
timer.schedule(new TimerTask() {
@Override
public void run() {
NameNodeAdapter.leaveSafeMode(dfsCluster.getNameNode());
}
}, rnd);
jettys.get(0).start();
waitForRecoveriesToFinish(DELETE_DATA_DIR_COLLECTION, false);
} finally {
timer.cancel();
}
}
}
@Override
public void actionPerformed(ActionEvent evt) {
plotterCache.remove(key);
Timer t = timerCache.remove(key);
t.cancel();
((XMBeanAttributes) table).collapse(attributeName, this);
}
@Override
public void recordClick2(final RFXComponent r, MouseEvent e, boolean withCellInfo) {
final JSONObject event = new JSONObject();
event.put("type", "click");
int button = e.getButton() == MouseButton.PRIMARY ? java.awt.event.MouseEvent.BUTTON1 : java.awt.event.MouseEvent.BUTTON3;
event.put("button", button);
event.put("clickCount", e.getClickCount());
event.put("modifiersEx", buildModifiersText(e));
double x = e.getX();
double y = e.getY();
Node source = (Node) e.getSource();
Node target = r.getComponent();
Point2D sts = source.localToScreen(new Point2D(0, 0));
Point2D tts = target.localToScreen(new Point2D(0, 0));
x = e.getX() - tts.getX() + sts.getX();
y = e.getY() - tts.getY() + sts.getY();
event.put("x", x);
event.put("y", y);
if (withCellInfo) {
event.put("cellinfo", r.getCellInfo());
}
final JSONObject o = new JSONObject();
o.put("event", event);
fill(r, o);
if (e.getClickCount() == 1) {
clickTimer = new Timer();
clickTimer.schedule(new TimerTask() {
@Override
public void run() {
sendRecordMessage(o);
}
}, timerinterval.intValue());
} else if (e.getClickCount() == 2) {
if (clickTimer != null) {
clickTimer.cancel();
clickTimer = null;
}
sendRecordMessage(o);
}
}
/** Test. */
@Test
public void testScheduleReportMail() {
final Timer timer = new Timer("test timer", true);
try {
final Counter counter = new Counter("http", null);
final Collector collector = new Collector("test", Collections.singletonList(counter));
MailReport.scheduleReportMailForLocalServer(collector, timer);
} finally {
timer.cancel();
}
// n'importe
assertNotNull("MailReport", timer.purge());
}
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
mTimer = new Timer();
while (true) {
DownloadRequest request = null;
try {
request = mQueue.take();
mRedirectionCount = 0;
shouldAllowRedirects = true;
Log.v("Download initiated for " + request.getDownloadId());
updateDownloadState(request, DownloadManager.STATUS_STARTED);
executeDownload(request, request.getUri().toString());
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
if (request != null) {
request.finish();
// don't remove files that have been downloaded sucessfully.
if (request.getDownloadState() != DownloadManager.STATUS_SUCCESSFUL) {
updateDownloadFailed(request, DownloadManager.ERROR_DOWNLOAD_CANCELLED, "Download cancelled");
}
}
mTimer.cancel();
return;
}
}
}
}
private static boolean hang1() throws IOException, InterruptedException {
// Time out was reproducible on Solaris 50% of the time;
// on Linux 80% of the time.
//
// Scenario: After fork(), parent executes and closes write end of child's stdin.
// This causes child to retain a write end of the same pipe.
// Thus the child will never see an EOF on its stdin, and will hang.
Runtime rt = Runtime.getRuntime();
// Increasing the iteration count makes the bug more
// reproducible not only for the obvious reason, but also for
// the subtle reason that it makes reading /proc/getppid()/fd
// slower, making the child more likely to win the race!
int iterations = 20;
int timeout = 30;
String[] catArgs = new String[] {"/bin/cat"};
String[] sleepArgs = new String[] {"/bin/sleep",
String.valueOf(timeout+1)};
Process[] cats = new Process[iterations];
Process[] sleeps = new Process[iterations];
Timer timer = new Timer(true);
TimeoutTask catExecutioner = new TimeoutTask(cats);
timer.schedule(catExecutioner, timeout * 1000);
for (int i = 0; i < cats.length; ++i) {
cats[i] = rt.exec(catArgs);
java.io.OutputStream s = cats[i].getOutputStream();
Process sleep = rt.exec(sleepArgs);
s.close(); // race condition here
sleeps[i] = sleep;
}
for (int i = 0; i < cats.length; ++i)
cats[i].waitFor(); // hangs?
timer.cancel();
destroy(sleeps);
if (catExecutioner.timedOut())
System.out.println("Child process has a hidden writable pipe fd for its stdin.");
return catExecutioner.timedOut();
}
public static void waitForJobExecutorToProcessAllHistoryJobs(ProcessEngineConfiguration processEngineConfiguration, ManagementService managementService,
long maxMillisToWait, long intervalMillis, boolean shutdownExecutorWhenFinished) {
ProcessEngineConfigurationImpl processEngineConfigurationImpl = (ProcessEngineConfigurationImpl) processEngineConfiguration;
if (processEngineConfigurationImpl.isAsyncHistoryEnabled()) {
AsyncExecutor asyncHistoryExecutor = processEngineConfiguration.getAsyncHistoryExecutor();
if (!asyncHistoryExecutor.isActive()) {
asyncHistoryExecutor.start();
}
try {
Timer timer = new Timer();
InterruptTask task = new InterruptTask(Thread.currentThread());
timer.schedule(task, maxMillisToWait);
boolean areJobsAvailable = true;
try {
while (areJobsAvailable && !task.isTimeLimitExceeded()) {
Thread.sleep(intervalMillis);
try {
areJobsAvailable = areHistoryJobsAvailable(managementService);
} catch (Throwable t) {
// Ignore, possible that exception occurs due to locking/updating of table on MSSQL when
// isolation level doesn't allow READ of the table
}
}
} catch (InterruptedException e) {
// ignore
} finally {
timer.cancel();
}
if (areJobsAvailable) {
throw new FlowableException("time limit of " + maxMillisToWait + " was exceeded");
}
} finally {
if (shutdownExecutorWhenFinished) {
asyncHistoryExecutor.shutdown();
}
}
}
}
private static boolean hang1() throws IOException, InterruptedException {
// Time out was reproducible on Solaris 50% of the time;
// on Linux 80% of the time.
//
// Scenario: After fork(), parent executes and closes write end of child's stdin.
// This causes child to retain a write end of the same pipe.
// Thus the child will never see an EOF on its stdin, and will hang.
Runtime rt = Runtime.getRuntime();
// Increasing the iteration count makes the bug more
// reproducible not only for the obvious reason, but also for
// the subtle reason that it makes reading /proc/getppid()/fd
// slower, making the child more likely to win the race!
int iterations = 20;
int timeout = 30;
String[] catArgs = new String[] {"/bin/cat"};
String[] sleepArgs = new String[] {"/bin/sleep",
String.valueOf(timeout+1)};
Process[] cats = new Process[iterations];
Process[] sleeps = new Process[iterations];
Timer timer = new Timer(true);
TimeoutTask catExecutioner = new TimeoutTask(cats);
timer.schedule(catExecutioner, timeout * 1000);
for (int i = 0; i < cats.length; ++i) {
cats[i] = rt.exec(catArgs);
java.io.OutputStream s = cats[i].getOutputStream();
Process sleep = rt.exec(sleepArgs);
s.close(); // race condition here
sleeps[i] = sleep;
}
for (int i = 0; i < cats.length; ++i)
cats[i].waitFor(); // hangs?
timer.cancel();
destroy(sleeps);
if (catExecutioner.timedOut())
System.out.println("Child process has a hidden writable pipe fd for its stdin.");
return catExecutioner.timedOut();
}
protected void launchBrowser(MediaPipeline mp, WebRtcEndpoint webRtcEp, PlayerEndpoint playerEp,
RecorderEndpoint recorderEp, String expectedVideoCodec, String expectedAudioCodec,
String recordingFile, Color expectedColor, int xColor, int yColor, int playTime)
throws InterruptedException {
Timer gettingStats = new Timer();
final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1);
getPage().subscribeEvents("playing");
getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY);
playerEp.play();
final CountDownLatch eosLatch = new CountDownLatch(1);
playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
eosLatch.countDown();
}
});
if (recorderEp != null) {
recorderEp.record();
}
// Assertions
String inRecording = recorderEp == null ? " in the recording" : "";
Assert.assertTrue("Not received media (timeout waiting playing event)" + inRecording,
getPage().waitForEvent("playing"));
if (recorderEp == null) {
// Checking continuity of the audio
getPage().activatePeerConnectionInboundStats("webRtcPeer.peerConnection");
gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, getPage()), 100,
200);
}
Assert.assertTrue(
"Color at coordinates " + xColor + "," + yColor + " must be " + expectedColor + inRecording,
getPage().similarColorAt(expectedColor, xColor, yColor));
Assert.assertTrue("Not received EOS event in player" + inRecording,
eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));
final CountDownLatch recorderLatch = new CountDownLatch(1);
if (recorderEp != null) {
saveGstreamerDot(mp);
recorderEp.stopAndWait(new Continuation<Void>() {
@Override
public void onSuccess(Void result) throws Exception {
recorderLatch.countDown();
}
@Override
public void onError(Throwable cause) throws Exception {
recorderLatch.countDown();
}
});
Assert.assertTrue("Not stop properly",
recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS));
// Wait until file exists
waitForFileExists(recordingFile);
AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec);
AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime),
TimeUnit.SECONDS.toMillis(getPage().getThresholdTime()));
} else {
gettingStats.cancel();
getPage().stopPeerConnectionInboundStats("webRtcPeer.peerConnection");
double currentTime = getPage().getCurrentTime();
Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime
+ " sec, real: " + currentTime + " sec) " + inRecording,
getPage().compare(playTime, currentTime));
if (recorderEp == null) {
Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets",
errorContinuityAudiolatch.getCount() == 1);
}
}
}
@Override
public void run() {
ExecutorService executor = Executors.newSingleThreadExecutor();
Timer timer = new Timer();
try {
for (DownloadModel downloadModel : mFilesToDownload) {
DownloadThread thread = new DownloadThread(downloadModel, this);
executor.submit(thread);
threads.add(thread);
}
checkDirectorySize(Aptoide.getConfiguration().getPathCacheApks());
mSize = getAllThreadSize();
TimerTask task = new TimerTask() {
public long mAvgSpeed;
/** How much was downloaded last time. */
private long iMLastDownloadedSize = mDownloadedSize;
/** The nanoTime last time. */
private long iMLastTime = System.currentTimeMillis();
private long iMFirstTime = System.currentTimeMillis();
@Override
public void run() {
long mReaminingSize = getAllSizeRemaining();
mDownloadedSize = getAllDownloadedSize();
mProgress = getAllProgress();
long timeElapsedSinceLastTime = System.currentTimeMillis() - iMLastTime;
long timeElapsed = System.currentTimeMillis() - iMFirstTime;
iMLastTime = System.currentTimeMillis();
// Difference between last time and this time = how much was downloaded since last run.
long downloadedSinceLastTime = mDownloadedSize - iMLastDownloadedSize;
iMLastDownloadedSize = mDownloadedSize;
if (timeElapsedSinceLastTime > 0 && timeElapsed > 0) {
// Speed (bytes per second) = downloaded bytes / time in seconds (nanoseconds / 1000000000)
mAvgSpeed = (mDownloadedSize) * 1000 / timeElapsed;
mSpeed = downloadedSinceLastTime * 1000 / timeElapsedSinceLastTime;
}
if (mAvgSpeed > 0) {
// ETA (milliseconds) = remaining byte size / bytes per millisecond (bytes per second * 1000)
mETA = (mReaminingSize - mDownloadedSize) * 1000 / mAvgSpeed;
}
Log.d("DownloadManager", "ETA: " + mETA + " Speed: " + mSpeed / 1000 + " Size: " + DownloadUtils.formatBytes(mSize) + " Downloaded: " + DownloadUtils.formatBytes(mDownloadedSize) + " Status: " + mStatusState + " TotalDownloaded: " + DownloadUtils.formatBytes(mProgress) + " " + System.identityHashCode(DownloadInfoRunnable.this));
download.setSpeed(getSpeed());
download.setTimeLeft(mETA);
download.setProgress(getPercentDownloaded());
BusProvider.getInstance().post(new OttoEvents.DownloadInProgress(download));
}
};
// Schedule above task for every (UPDATE_INTERVAL_MILLISECONDS) milliseconds.
timer.schedule(task, 0, UPDATE_INTERVAL_MILLISECONDS);
executor.shutdown();
// Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs,
// or the current thread is interrupted, whichever happens first.
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
timer.cancel();
timer.purge();
mSize = getAllThreadSize();
mProgress = getAllProgress();
Log.d("download-trace", "Downloads done " + mSize + " " + mProgress + " " + mStatusState.getEnumState().name());
download.setSpeed(getSpeed());
download.setProgress(getPercentDownloaded());
if (mStatusState instanceof ActiveState) {
changeStatusState(new CompletedState(this));
autoExecute();
Analytics.DownloadComplete.downloadComplete(download);
}
} catch (Exception e) {
changeStatusState(new ErrorState(this, EnumDownloadFailReason.NO_REASON));
e.printStackTrace();
}
BusProvider.getInstance().post(new OttoEvents.DownloadEvent(getId(), mStatusState));
downloadManager.updatePendingList();
threads.clear();
mDownloadedSize = 0;
mSpeed = 0;
mETA = 0;
Logger.d("download-trace", "Download Finish??" + download.getName());
}