欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring定时器配置

程序员文章站 2022-06-09 11:00:16
...

目录

搭建好spring环境

导入quartz-all-2.1.5.jar

定时器beans-quarz-packet.xml配置

web.xml引入beans-quarz-packet.xml

编写定时器类TimeTask

测试,重启服务,监测控制台


搭建好spring环境

导入quartz-all-2.1.5.jar

spring定时器配置

定时器beans-quarz-packet.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- ============================= Spring Quartz ================================ -->
    <bean id="timeTask" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.dcits.quartz.TimeTask" />
        <property name="jobDataAsMap">
            <map>
                <entry key="timeout">
                    <value>60</value>
                </entry>
            </map>
        </property>
    </bean>
    <!-- 每两秒执行一次-->
    <bean id="timeRunTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="timeTask" />
        </property>
        <property name="cronExpression">
            <value>0/2 * * * * ? </value>
        </property>
    </bean>
    <!-- ########  总调配中心 ########## -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref local="timeRunTaskTrigger" />
             </list>
        </property>
    </bean>    
</beans>

web.xml引入beans-quarz-packet.xml

 <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml, classpath:beans-quarz-packet.xml
        </param-value>
  </context-param>

编写定时器类TimeTask

package com.dcits.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeTask implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String day = format.format(date);
        System.out.println(day + "打卡");
    }
}

 

测试,重启服务,监测控制台

spring定时器配置

相关标签: java