定时器 Timer
在jdk的库中,Timer工具类的主要作用是设置计划任务的,旨在指定的时间开始执行某一个任务。
TimerTask类为抽象类,主要作用是封装任务的。
Timer对应的方法:
schedule(TimerTask task, Date time)
该方法的作用为在指定的日期执行一次某个任务。若是执行任务时间晚于当前时间,表明该任务在将来执行。若是执行任务时间早于当前时间,表明该任务会立即执行。
schedule(TimerTask task, Date firstTime, long period)
该方法的作用为在指定的日期之后按指定的时间间隔无限循环执行某个任务。若是执行任务时间晚于当前时间,表明该任务在将来执行。若是执行任务时间早于当前时间,表明该任务会立即执行。
cancel()
该方法的作用为终止该计时器。Timer类中的该方法会将任务队列中的全部任务清空。
TimerTask
cancel()
该方法的作用为终止该计时器。TimerTask类中的该方法只清除自身任务。
例子:
public class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("1122222222");
}
}
public class Test1 {
private static Log log = LogFactory.getLog(Test1.class);
public static void main(String[] args) {
long newTime = System.currentTimeMillis();
log.info("newTime:" + newTime);
long scheduleTime = (newTime - 5000);
log.info("scheduleTime:" + scheduleTime);
MyTask myTask = new MyTask();
Timer timer = new Timer();
timer.schedule(myTask, new Date(scheduleTime));
}
}
结果:
2021-06-16 20:26:36,019 [timer.Test1.main(Test1.java:15)]-[INFO] newTime:1623846396018
2021-06-16 20:26:36,025 [timer.Test1.main(Test1.java:19)]-[INFO] scheduleTime:1623846391018
1122222222
在输出完结果后,可以看到下图中任务虽然结束,但是进程还没有销毁。
现象:
原因:
在new Timer()时启动了一个新的非守护线程
// 在创建Timer时,调用完无参构造函数后调用一参构造函数,在一参构造函数里会开启一个新的线程。
Timer timer = new Timer();
/**
* Creates a new timer. The associated thread does <i>not</i>
* {@linkplain Thread#setDaemon run as a daemon}.
*/
public Timer() {
this("Timer-" + serialNumber());
}
/**
* Creates a new timer whose associated thread has the specified name.
* The associated thread does <i>not</i>
* {@linkplain Thread#setDaemon run as a daemon}.
*
* @param name the name of the associated thread
* @throws NullPointerException if {@code name} is null
* @since 1.5
*/
public Timer(String name) {
thread.setName(name);
thread.start();
}