import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
private Timer timer = new Timer();
// 启动计时器 延迟3s,每0.5s执行1次
public void launchTimer() {
timer.schedule(new TimerTask() {
public void run() {
System.out.println("hello world-1:" + System.currentTimeMillis());
throw new RuntimeException();
}
}, 1000 * 3, 500);
}
// 向计时器添加一个任务,延迟1s,每5s执行一次
public void addOneTask() {
System.out.println("hello world-2-1:" + System.currentTimeMillis());
timer.schedule(new TimerTask() {
public void run() {
System.out.println("hello world-2-2:" + System.currentTimeMillis());
}
}, 1000 * 1, 1000 * 5);
}
public static void main(String[] args) throws Exception {
TimerTest test = new TimerTest();
test.launchTimer();
Thread.sleep(1000 * 5);// 5秒钟之后添加一个新任务
test.addOneTask();
}
}
输出:
hello world-1:1623314074261
Exception in thread "Timer-0" java.lang.RuntimeException
at com.company.TimerTest$1.run(TimerTest.java:14)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
hello world-2-1:1623314076261
Exception in thread "main" java.lang.IllegalStateException: Timer already cancelled.
at java.util.Timer.sched(Timer.java:397)
at java.util.Timer.schedule(Timer.java:248)
at com.company.TimerTest.addOneTask(TimerTest.java:22)
at com.company.TimerTest.main(TimerTest.java:34)
分析:定时任务1执行完,输出,会抛出运行时异常。此时timer已经是cancelled状态。再执行定时任务2,就会抛出Timer already cancelled异常。
解决的办法:1.定时任务里捕获异常 2.使用ScheduledExecutorService
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public ScheduledExecutorService scheduleExec = Executors.newScheduledThreadPool(1);
//启动计时器
public void launchTimer() {
Runnable task = new Runnable() {
public void run() {
System.out.println("hello world-1:" + System.currentTimeMillis());
throw new RuntimeException();
}
};
scheduleExec.scheduleWithFixedDelay(task, 1000 * 5, 1000 * 10, TimeUnit.MILLISECONDS);
}
//添加新任务
public void addOneTask() {
System.out.println("hello world-2-1:" + System.currentTimeMillis());
Runnable task = new Runnable() {
public void run() {
System.out.println("hello world-2-2:" + System.currentTimeMillis());
}
};
scheduleExec.scheduleWithFixedDelay(task, 1000 * 1, 1000, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) throws Exception {
Main test = new Main();
test.launchTimer();
Thread.sleep(1000 * 5);//5秒钟之后添加新任务
test.addOneTask();
}
}
输出:
hello world-2-1:1623313863678
hello world-1:1623313863679
hello world-2-2:1623313864679
hello world-2-2:1623313865681
hello world-2-2:1623313866682
...
网友评论