maven坐标:
<!-- quartz定时任务-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>
<!--spring拓展-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
spring-jobs.xml:spring配置文件
Cron表达式在线解析
<?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"
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">
<!--包扫描-->
<context:component-scan base-package="top.zhenghy123.jobs"/>
<!-- 注册JobDetail,作用是负责通过反射调用指定的Job -->
<bean id="JobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!--调哪个对象的哪个方法-->
<!--注入对象-->
<property name="targetObject" ref="testJob"/>
<!--注入方法-->
<property name="targetMethod" value="test"/>
</bean>
<!--注册一个触发器,指定任务触发的时间(间隔)-->
<bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobDetail"/>
<property name="cronExpression">
<!-- 每隔10秒执行一次任务 0/10 * * * * ? -->
<!--每天凌晨2点执行任务 0 0 2 ? * *-->
<!--Cron表达式-->
<value>0/10 * * * * ?</value>
</property>
</bean>
<!--注册一个统一调用工厂,通过这个调度工厂调度任务-->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="jobTrigger"/>
<!--可有多个触发器-->
</list>
</property>
</bean>
</beans>
定时任务类:
@Component
public class TestJob {
/**
* 测试定时任务
*/
public void test(){
System.out.println("我被执行了...");
}
}