一、首先引入quarz所需要的jar包,如下:
org.quartz-scheduler
quartz
1.8.6
二、编写定时任务
定义一个普通的JAVA类,不需要继承或者实现其它的父类
package com.liyi.test.quarz;
import java.util.Date;
public class SpringQuarz {
public void test(){
System.out.println(new Date()+"触发一次定时任务");
}
}
三、spring配置定时任务,我是自己在web-inf下面新建了一个文件夹,专门放置quarz定时任务的配置文件,在主的spring配置文件applicationContent.xml中import单个的定时任务。
1、在applicationContext.xml中,引入定时任务
2、定时任务详细配置(一定要记得加入对应的命名空间)
以下是我个人理解,你要配置一个定时任务,需要定义四部分主要内容:
a)你需要把你的定时任务类加入到spring 容器 中,你可以用注解,也可以用配置bean的方式。
b)org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ,配置一个详细调度任务的配置。
里面有两个参数,一个是 targetObject:引用你的定时任务类 一个是targetMethod :定时任务类里面的执行方法
c) org.springframework.scheduling.quartz.CronTriggerBean,调度器的配置,说白了就是指定任务的调度时间里面也
有两个参数,一个是jobDetail:对应你配置详细调度任务的bean 一个是 cronExpression 执行时间
d)org.springframework.scheduling.quartz.SchedulerFactoryBean 触发任务的工厂。里面也有两个参数一个是
jobDetails:对应的是你的任务调度详细配置,一个是triggers就是调度器的时间,这两个就是指向你刚才配的两个bean
就对了。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
test
启动项目,项目就会每隔5秒执行一下你的定时任务。