spring3.0定时任务 (一) 简单示例

        在项目中经常用到的spring的一个功能就是定时任务,它可以自动监视时间,到点就执行,给程序带来了很大的方便,很多地方都会需要这种功能,比如做数据备份、同步等操作。最近一直比较忙,主要是比较懒,今天把这部分稍作小结。

       使用spring定时任务的前提:项目中已经搭建好了spring环境(我用的是spring3.0)。

       一、基本使用:

        spring的定时任务使用起来十分方便,只需要两步:1、写好执行定时任务的类和方法;2、配置spring定时任务配置文件:

        1、写好执行定时任务的类和方法:

package com.test;

public class Test {

	public void test() {
		System.out.println("执行定时任务的方法。");
	}
}
        2、配置spring的定时任务配置文件(可以新建一个xml文件,也可以在已经有的xml文件中配置)

配置文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
       
		<!--必须,QuartzScheduler 延时启动,应用启动后 QuartzScheduler 再启动-->
		<property name="startupDelay" value="60"/>		
		<!-- 普通触发器 :触发器列表-->
		<property name="triggers">
			<list>				
				<ref local="testTrigger"/>
			</list>
		</property>
    </bean>

<!-- 配置执行定时任务的类和方法 --> 
    <bean id="testDetail"  
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
        <property name="targetObject">  
            <bean class="com.test.Test"></bean>
        </property>  
        <property name="targetMethod">  
            <value>test</value>  
        </property>  
    </bean>
<!-- 配置触发器 -->   
    <bean id="testTrigger"  
        class="org.springframework.scheduling.quartz.CronTriggerBean">  
        <property name="jobDetail">  
            <ref bean="testDetail"/> <!-- 触发器触发的 执行定时任务的bean -->   
        </property>  
        <property name="cronExpression">  
            <!-- 每天23时   -->  <!-- 定时任务执行的间隔 --> 
            <value>0 0 23 * * ?</value>
        </property>  
    </bean>  
</beans>
       二、spring定时任务的执行间隔配置、多个定时任务的配置(请点击)

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值