spring定时器quartz的实现实例

本文详细介绍了如何在Spring框架中配置基于Quartz的定时任务。通过XML配置方式,设置了定时器myTimer,定义了目标bean及其执行方法executeMethod,并通过Cron表达式设置了调度触发器,实现了每20分钟执行一次的任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说,直接上代码,如下
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-4.1.xsd">

    <!--############################ 定时器myTimer ############################-->

    <!-- 使用MethodInvokingJobDetailFactoryBean,任务类可以不实现Job接口,通过targetMethod指定调用方法 -->
    <bean id="myTimer" class="com.nj.nfhy.util.timer.MyTimer" />
    <!-- 定义目标bean和bean中的方法 -->
    <bean id="myTimerMethod"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myTimer" />
        <!-- 要执行的方法名称 -->
        <property name="targetMethod" value="executeMethod" />
    </bean>
    <!-- ================================== 调度触发器 ============================== -->
    <bean id="myTimerCronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="myTimerMethod"></property>
        <property name="cronExpression">
            <value>*/20 * * * * ?</value>
        </property>
    </bean>

    <!--    放到Scheduler容器中   -->
    <bean id="SpringJobSchedulerFactoryBean"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="myTimerCronTriggerBean" />
            </list>
        </property>
    </bean>
</beans>

关于调度时间怎么设置,请自行百度,此处忽略。

MyTimer.java

package com.nj.nfhy.util.timer;

public class MyTimer {

    public void executeMethod() {
        System.out.println(System.currentTimeMillis());
        System.out.println("timer");
    }
}

补充:
1.spring定时器org.springframework.scheduling.quartz.*是基于JAVA的quartz实现的。
2.定时器主要部分:scheduler、jobdetail、trigger,表示在调度容器(scheduler)中,定时什么时候(trigger),执行具体的任务(jobdetail)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值