任务调度(三):Quartz

it2025-10-07  9

1、Quartz

Quartz是Job Scheduling(任务调度)领域的开源项目,可单独使用,也可和JavaSE,EE进行组合,是一个任务调度管理系统,可在特定的时间内执行特定的任务,如想在Java中使用Quartz,则只需将Quartz的jar包导入到项目中即可。

完全由Java开发,可以用来执行定时任务

2、修改beans.xml
<import resource="spring-quartz.xml"/>
3、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 https://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger" /> </list> </property> </bean> <!-- 2.trigger:触发器 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"> <ref bean="jobdetail" /> </property> <property name="cronExpression"> <!-- cron表达式:在每天早上8点到晚上8点期间每1分钟触发一次 --> <!-- <value>0 0/1 8-20 * * ?</value> --> <!-- 每周6凌晨2点触发一次 --> <!-- <value> 0 0 2 0 0 6 *</value> --> <!-- cron表达式:每10秒触发一次 --> <value>0/10 * * * * ?</value> </property> </bean> <!-- 3.jobdetail: 调度的任务的详情--> <bean id="jobdetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject" ref="quartzJob" /> <!-- 调用类中的方法名称 --> <property name="targetMethod"> <value>work</value> </property> </bean> <!-- 4.job:真正执行的调度任务 --> <bean id="quartzJob" class="com.cc.service.impl.CalcCustLostService" /> </beans>
4、CalcCustLostService
package com.cc.service.impl; import com.cc.entity.Orders; import com.cc.mapper.OrdersMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CalcCustLostService { private Logger log = LoggerFactory.getLogger(CalcCustLostService.class); @Autowired private OrdersMapper ordersMapper; public void work() { System.out.println("我是定时任务....."); } }

下一章:任务调度(二):Spring&SpringBoot任务调度工具/cron表达式

最新回复(0)