使用quartz实现定时任务三步走
一、pom.xml配置
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
二、beans-task.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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/p
http://www.springframework.org/schema/p/spring-p.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
**<!--要执行的任务 -->**
<bean name="HelloTask" class="com.yc.tasks.HelloTask"/>
<bean id="helloJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="HelloTask"/>
<property name="targetMethod" value="sayHello"/>
</bean>
**<!--执行的频率 -->**
<bean id="cronTrigger1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="helloJobDetail"/>
**<!--每10秒显示一次 -->**
<property name="cronExpression" value="1/10 * * * * ?"/>
</bean>
**<!-- 将任务和频率组合到计划中 -->**
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger1"/>
</list>
</property>
</bean>
</beans>
三、业务层测试
package com.yc.tasks;
import org.springframework.stereotype.Component;
@Component
public class HelloTask {
public void sayHello(){
System.out.println("hello world");
}
}
四、运行结果