Java定时器

1、jdk  Timer定时器

    web启动后定期执行

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

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * jdk定时器,web启动后定期执行
 * web.xml需要配置 
 *<listener>
 *	<listener-class>AutoRun</listener-class>
 *</listener>
 * @author thrillerzw
 * 
 */
public class AutoRun implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("销毁!");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		//计时器
		Timer timer = new Timer();
		//public abstract class TimerTask extends Object implements Runnable
		//计时器任务:由 Timer 安排为一次执行或重复执行的任务。
		//安排指定的任务在指定的时间开始进行重复的固定延迟执行:schedule(TimerTask task, Date firstTime, long period) 
		//安排在指定的时间执行指定的任务:schedule(TimerTask task, Date time) 
		// 安排指定的任务从指定的延迟后开始进行重复的固定延迟执行:schedule(TimerTask task, long delay, long period) 
         
		TimerTask timerTask = new TimerTask(){

			@Override
			public void run() {
				System.out.println("定时器任务运行中");
			}
			
		};
		//0毫秒延迟,间隔100毫秒执行一次
		timer.schedule(timerTask, 0, 100);
		
	}

}

   详解参考:Timer和TimerTask详解  http://blog.csdn.net/ahxu/article/details/249610

 

你可能感兴趣的:(java)