Java中定时任务的实现
1. 建立TimerTask
?
package com.yingxia.asset.server.message_notice;import java.util.Date;import java.util.TimerTask;public class MessageTask extends TimerTask {@SuppressWarnings("deprecation")@Overridepublic void run() {System.out.println(new Date().toLocaleString() + "执行短信任务");}}?
2. 建立ServletContextListener
?
package com.yingxia.asset.server.message_notice;import java.util.Date;import java.util.Timer;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import com.yingxia.server.commom.FileReader;public class MessageTaskListener implements ServletContextListener {private Timer timer = null;@Overridepublic void contextDestroyed(ServletContextEvent sce) {timer.cancel();System.out.println("短信任务定时器停止");}@SuppressWarnings("deprecation")@Overridepublic void contextInitialized(ServletContextEvent sce) {// 86400000 毫秒 = 1天Date d = new Date(new Date().getTime() + 86400000);String[] strs = readFirstLine().split(":");d.setHours(Integer.valueOf(strs[0]));d.setMinutes(Integer.valueOf(strs[1]));d.setSeconds(0);System.out.println("短信任务的启动时间:" + d.toLocaleString());timer = new Timer(true);timer.schedule(new MessageTask(), d, 86400000);}private String readFirstLine() {return FileReader.getFirstLine("com/yingxia/asset/server/message_notice/SetTime");}}?
3. 配置web.xml
?
<!-- 短信listener --><listener><listener-class>com.yingxia.asset.server.message_notice.MessageTaskListener</listener-class></listener>?
?