spring定时任务(quartz-scheduler)

1.在pom.xml里引入quartz.jar

<dependency>

            <groupId>org.quartz-scheduler</groupId>

            <artifactId>quartz</artifactId>

            <version>2.2.1</version>

        </dependency>



2.创建spring-quartz.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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"

       default-autowire="byName">

       

       <bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

       <property name="jobFactory">

       <bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />

       </property>

       <property name="triggers">

       <list>

       <ref bean="myTrigger" />

       </list>

       </property>

       </bean>

       

       <bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">

       <property name="cronExpression" value="0/5 * * * * ?" />  //时间格式: 秒 分 时 日 月 年

       <property name="jobDetail" ref="myTriggerDetail" /> 

       </bean>

       <bean id="myTriggerDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

       <property name="targetObject" ref="myTriggerJob" /> //job的执行类

       <property name="targetMethod" value="execute" />  //job的执行方法

       <property name="concurrent" value="false" />

       </bean>

       <bean id="myTriggerJob" class="com.moin.web.service.job.MyTriggerJob" />

</beans>

注:SchedulerFactoryBean的数据源属性叫datasource, 所以应该避免spring配置的数据源叫datasource。


3. 在contextConfigLocation定义的spring-context.xml配置文件里引入spring-quartz.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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"

  default-autowire="byName">

  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="location" value="classpath:dbcp-config.properties" />

  </bean>

  <import resource="spring-datasource-jdbc.xml" />

  <import resource="spring-dao.xml" />

  <import resource="spring-service.xml" />

  <import resource="spring-quartz.xml" />

</beans>


4, 执行job的类:MyTriggerJob:

public class MyTriggerJob {

public void execute() {

//todo something...

}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值