Files
notes_estom/Java/JavaDemo/codedemo/java/util/timer/TimerDemo.java
2025-09-14 03:49:42 -04:00

48 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cn.aofeng.demo.java.util.timer;
import java.util.Timer;
import java.util.TimerTask;
import cn.aofeng.demo.util.DateUtil;
/**
* {@link Timer}的使用示例:<br>
* 定时任务1执行过程中会抛出异常。<br>
* 定时任务2执行过程中不会抛出异常。<br>
* <br>
* 目的检测java.util.Timer在执行定时任务的过程中任务内抛出异常没有捕捉时在下一次执行时间到来时是否可以正常执行。<br>
* 测试的JDK版本1.6.xx。<br>
* 结果不通过定时任务抛出异常时整个Timer中止其他定时任务也中止。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class TimerDemo {
public static void main(String[] args) {
Timer timer = new Timer("aofeng-timer-demo");
timer.schedule(new ThrowExceptionTask(), DateUtil.getNextMinute(), 60*1000);
timer.schedule(new NotThrowExceptionTask(), DateUtil.getNextMinute(), 60*1000);
}
static class ThrowExceptionTask extends TimerTask {
@Override
public void run() {
System.out.println("任务名:ThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
throw new IllegalArgumentException();
}
} // end of ThrowExceptionTask
static class NotThrowExceptionTask extends TimerTask {
@Override
public void run() {
System.out.println("任务名:NotThrowExceptionTask, 当前时间:"+DateUtil.getCurrentTime());
}
} // end of NotThrowExceptionTask
}