java中Timer定时器的使用和启动

一.概述

定时计划任务功能在Java中主要使用的就是Timer对象,它在内部使用多线程的方式进行处理,所以它和多线程技术还是有非常大的关联的。在JDK中Timer类主要负责计划任务的功能,也就是在指定的时间开始执行某一个任务,但封装任务的类却是TimerTask类。

二.应用场景

我们使用timer的时候,一般有4种情况:
1.指定时间执行;
2.指定时间执行后间隔指定时间重复执行;
3.启动任务之后多久执行;
4.启动任务后多久执行,执行之后指定间隔多久重复执行

三.使用方法

1.首先要通过继承 TimerTask 类 并实现 run() 方法来自定义要执行的任务(当然也可以写成匿名内部类),
2.需要创建一个定时器(Timer类对象),并通过Timer.schedule(TimerTask task,Date time) 方法执行时间运行任务
具体代码如下:

package timerdemo;

import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo {
	public static void main(String[] args) {
		timerTest();
	}
	
	public static void timerTest(){
		//创建一个定时器
		Timer timer = new Timer();
		//schedule方法是执行时间定时任务的方法
		timer.schedule(new TimerTask() {
			
			//run方法就是具体需要定时执行的任务
			@Override
			public void run() {
				System.out.println("timer测试!!!");
			}
		}, 1000, 10000);
	}
}

这里的 schedule方法有4个,分别对应上面说的四种情况:


四.启动方法

1.在jar工程下启动
把jar工程打成jar包,通过java -jar timer.jar 运行

2.这web工程下启动
spring中我们可以通过实现接口ApplicationListener,并重写public void onApplicationEvent(ApplicationEvent event) {}可以在容器初始话的时候执行这个方法
下面展示下web工程下每天00:00执行任务的代码:
 

@Component
public class SystemInitListener implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		
		//创建定时器
		Timer timer = new Timer();
		Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE),0,0,0);
        long timeInterval = 24 * 60 * 60 * 1000;
        timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// 每天00:00需要做的事情
				
			}
		}, calendar.getTime(), timeInterval);

猜你喜欢

转载自blog.csdn.net/iteen/article/details/81808098