Spring + Quartz 实现定时器

Spring + Quartz 实现定时器

相关文章链接:

IDEA使用Maven搭建SSM框架Web项目

观前提示:

本文所使用的IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Tomcat版本为9.0.12。

本文使用的jar包版本为springframework4.3.18.RELEASE和quartz2.3.2。

定时器类 Timer.java

package com.example.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Timer {
    
    
    public void TimerTask(){
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("定时任务,时间为:" + sdf .format(new Date()));
    }
}

applicationContext.xml定时器部分配置为

	<bean name="task" class="com.example.controller.Timer"/>
        <bean id="taskDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
            <!-- 执行的类 -->
            <property name="targetObject" ref="task"/>
            <!-- 执行的类中的方法 -->
            <property name="targetMethod" value="TimerTask"/>
        </bean>
        <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
            <property name="jobDetail" ref="taskDetail"/>
            <!-- 每一秒钟执行一次 -->
            <property name="cronExpression" value="0/1 * * * * ?">
            </property>
        </bean>

        <!-- 总配置 -->
        <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
            <!-- 添加触发器 -->
            <property name="triggers">
                <list>
                    <ref bean="cronTrigger"/>
                </list>
            </property>
        </bean>

启动服务,运行效果如下图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43611145/article/details/105142375