Spring中任务调度(TimerTask篇)

本文介绍如何在Spring框架中实现定时任务调度,通过配置XML文件来管理TimerTask,并演示了一个简单的例子,展示了如何设置任务的触发间隔及启动方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring中实现按时任务调度除了用Quartz之外,还可以使用TimerTask。但是TimerTask适用于时间间隔相对较短的任务,如果任务时间间隔很长,比如一天执行一次,还是用Quartz要好。

1.xml文件

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >

< beans >
    
<!--  定时执行任务的类,要继承TimerTask  -->
    
< bean  id ="UserTimerTask"  class ="task.UserTimerTask" />
    
    
<!--  用Spring管理这个TimerTask,设定触发间隔  -->
    
< bean  id ="ScheduledUserTimerTask"  class ="org.springframework.scheduling.timer.ScheduledTimerTask" >
      
< property  name ="delay" >
        
< value > 3000 </ value >
      
</ property >
      
< property  name ="period" >
        
< value > 3000 </ value >
      
</ property >
      
< property  name ="timerTask" >
        
< ref  local ="UserTimerTask" />
      
</ property >
    
</ bean >
    
    
<!--  启动TimerTask,TimerFactoryBean会在上下文初始化的时候自动启动task,在销毁时,自动结束task  -->
    
< bean  id ="timerFactory"  class ="org.springframework.scheduling.timer.TimerFactoryBean" >
     
< property  name ="scheduledTimerTasks" >
      
< list >
        
< ref  local ="ScheduledUserTimerTask" />
      
</ list >
     
</ property >
   
</ bean >
</ beans >


2.Task类

package  task;

import
 java.util.TimerTask;

public   class  UserTimerTask  extends  TimerTask 
{

    @Override
    
public   void  run()  ...
{
        
//  TODO Auto-generated method stub

        System.out.println( " Task started! " );
    }


}

...


3.测试类

package  test;

import
 org.springframework.context.ApplicationContext;
import
 org.springframework.context.support.ClassPathXmlApplicationContext;

public   class  TimerTaskTest 
{

    
public   static   void  main(String[] args)  ...
{
        
//  TODO Auto-generated method stub

         System.out.println( " Test start! " );
         ApplicationContext ctx 
=   new  ClassPathXmlApplicationContext( " xml/TimerTask.xml "
);
         
         
// 保持运行,才能看到效果

          while  ( true );
    
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值