spring定时器(一)

此文章是基于  搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台

一. jar包介绍

  1. spring-framework-4.3.4.RELEASE 的 libs 文件夹下得到:

spring-context-support-4.3.4.RELEASE.jar

  2. quartz-2.2.3.jar

二. 相关文件介绍

  1. applicationInfrastructure.xml,定时器配置文件

    spring的bean类无法在定时器中自动注入,需要在配置中手动添加 。<property name="jobDataAsMap">

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 定义定时器任务 -->
<bean id="fixTimeJob"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<!-- 指定任务对应的类 -->
<property name="jobClass" value="com.ims.infrastructure.quartz.FixTimeJob" />
<!-- 往任务中注入bean -->
<property name="jobDataAsMap">
<map> </map>
</property>
</bean> <!-- 定义任务的触发器 -->
<bean id="fixTimeJobTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="fixTimeJob" />
<!-- 重复执行间隔时间(毫秒) -->
<property name="repeatInterval" value="30000"/>
<!-- 服务启动后多久执行(毫秒) -->
<property name="startDelay" value="1000"/>
</bean> <!-- 需要被执行的触发器集合 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="fixTimeJobTrigger"/>
</list>
</property>
</bean> </beans>

  2. FixTimeJob.java,定时器任务类

package com.ims.infrastructure.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean; public class FixTimeJob extends QuartzJobBean{ @Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
System.out.println("hello!");
} }

三. 测试
  启动服务,按照定时器配置文件设置的时间间隔,在后台每30秒输出"hello!"

上一篇:https证书申请流程和简介


下一篇:kafka单机安装和启动