java,web定时器

定时器

步骤

1.  导入定时器需要的jar包:

2.写一个类,继承TimerTask类,重写其run()方法;

3.在run()方法里写需要定时执行的任务;

4.写一个类管理定时器任务,实现ServletContextListener接口

5.重写contextInitialized方法,在此方法里创建Timer对象,调用Timer的schedule()方法执行定时器任务;

6.在web.xml文件里配置管理定时器任务的类的路径;

示例如下:

importjava.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;

publicclass MyTest1extends TimerTask{
   
privateSimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
 @Override
 public void run() {
     
System.out.println("现在时间是:"+sf.format(new Date()));
 }

}

第二步:编写一个类,该类实现ServletContextListener接口

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

publicclass TimerTaskManagerimplements ServletContextListener{
  
private  Timer timer;
 @Override
 public void contextInitialized(ServletContextEventsce) {
  System.out.println("
程序定时执行任务.....................................");
  MyTest1 t=new MyTest1();
       
timer=newTimer("开始执行任务",true);//
      
timer.schedule(t,0,1000);//执行MyTest1中的run方法,t代表TimerTask的子类,0代表延迟0毫秒执行run方法,1000表示每隔一秒执行一次run方法,后面两个参数可根据自己的需求而定义

 }

 @Override
 public void
contextDestroyed(ServletContextEventsce) {
  System.out.println("
程序定时执行任务结束.....................................");
  timer.
cancel();
 }

}

Web.xml配置:

<listener>

      <listener-class>timer.TimerTaskManager</listener-class>

  </listener>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值