JSP程序中Listener和Timer的运用

本文介绍如何使用Java中的Timer和TimerTask实现定时任务,通过ServletContextListener监听上下文初始化和销毁,实现实时检查程序运行状态。适用于需要定时执行如统计流量、更新缓存等任务的场景。

    有的时候需要在程序运行时,定时执行一些程序,比如说统计流量、更新缓存数据等,通常要使用Listener和Timer,下面就是一个简单应用,目的就是时刻检查程序是否正在执行当中。

    首先创建一个TimerTask

ContractedBlock.gifExpandedBlockStart.gifCode
ExpandedBlockStart.gifContractedBlock.gifpublic class LogTask extends TimerTask {
    @Override
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void run() {
        
// TODO Auto-generated method stub
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println( sdf.format(
new Date()) + "--this programe is running!");
        
    }

}

   接着创建监听程序

ContractedBlock.gifExpandedBlockStart.gifCode
ExpandedBlockStart.gifContractedBlock.gifpublic class LogListener implements ServletContextListener {
    
private Timer timer = null;
    @Override
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void contextDestroyed(ServletContextEvent arg0) {
        
// TODO Auto-generated method stub
        if (timer != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            timer.cancel();
        }

    }


    @Override
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public void contextInitialized(ServletContextEvent arg0) {
        
// TODO Auto-generated method stub
        if (timer == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            timer 
= new Timer();
            timer.schedule(
new LogTask(), new Date(), 1000);
        }

    }


}

   在web.xml配置

<listener>
      
<listener-class>org.heroking.web.LogListener</listener-class>
  
</listener>

 

转载于:https://www.cnblogs.com/heroking2000/archive/2009/10/23/1588895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值