如何定时执行servlet   Leave a comment

触发类—

  1. import java.util.Timer;
  2. import javax.servlet.ServletContextEvent;
  3. import javax.servlet.ServletContextListener;
  4. public class TimerTestAction implements ServletContextListener{
  5. private Timer timer;
  6. public void contextDestroyed(ServletContextEvent servletcontextevent) {
  7. timer.cancel();
  8. servletcontextevent.getServletContext().log(“定时器销毁~~~”);
  9. System.out.println(“定时任务结束~~”);
  10. }
  11. public void contextInitialized(ServletContextEvent servletcontextevent) {
  12. System.out.println(“定时任务开始~~”);
  13. timer = new Timer(true);
  14. timer.schedule(new TimerRunAction(servletcontextevent.getServletContext()), 0, 5*1000);
  15. }
  16. }

定时器—-

  1. import java.util.Calendar;
  2. import java.util.TimerTask;
  3. import javax.servlet.ServletContext;
  4. public class TimerRunAction extends TimerTask{
  5. private static final int C_SCHEDULE_HOUR = 0;
  6. private static boolean isRunning = false;
  7. private ServletContext context = null;
  8. public TimerRunAction(ServletContext context){
  9. this.context = context;
  10. }
  11. @Override
  12. public void run() {
  13. Calendar c = Calendar.getInstance();
  14. if(!isRunning){
  15. if(C_SCHEDULE_HOUR == c.get(Calendar.HOUR_OF_DAY)){
  16. context.log(“kaishi zhixing zhiding renwu~~”);
  17. }
  18. else{
  19. context.log(“shangyici renwu zhixing haiwei jieshu~~~”);
  20. }
  21. }
  22. }
  23. }

 

 

Posted 2011年03月20日 by gw8310 in 未分类

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: