Spring定时器技术终结者——采用XML配置的方式实现Spring定时器

        在Spring中有两种方式可以实现定时器的功能,分别是Scheduled注释方式和XML配置方式,本博客将介绍如何在Spring中使用采用XML配置的方式实现定时器的功能,代码及相应的解释如下:

        代码1—Spring配置文件(applicationContext.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" 
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/task
          http://www.springframework.org/schema/task/spring-task.xsd">

	<bean id="jobDispatcher" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject"><!-- 指定调度对象 -->
			<bean class="com.ghj.packageoftimer.SpringTimerTest" />
		</property>
		<property name="targetMethod" value="test" /><!-- 指定定时器执行调度对象中的那个方法,该方法的访问权限也可以是私有的 -->
		<property name="concurrent" value="false" /><!-- 配置job是否可以并行运行 -->
	</bean>

	<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail" ref="jobDispatcher" />
		<property name="cronExpression" value="0 0/1 * * * ?" /><!-- cronExpression用于指明该方法被调用的时机 -->
	</bean>

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list><!-- 通过在list标签中的ref标签可以放置一个或多个触发器 -->
				<ref bean="cronTrigger" />
			</list>
		</property>
	</bean>
</beans>

        代码2——Spring定时器测试类(SpringTimerTest.java文件):

package com.ghj.packageoftimer;

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

/**
 * Spring定时器测试类
 * 
 * @author 高焕杰
 */
public class SpringTimerTest{

	/**
	 * Spring定时器测试方法
	 * 
	 * @author 高焕杰
	 */
    public void test(){
    	System.err.println(new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒").format(new Date()));
    }
}

        代码3——加载Spring配置文件并启动Spring定时器的类(StartSpringTimer.java文件):

package com.ghj.packageoftest;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 加载Spring配置文件,启动Spring定时器
 * 
 * @author 高焕杰
 */
public class StartSpringTimer {

	public static void main(String[] args){
		new ClassPathXmlApplicationContext("conf/spring/applicationContext.xml");
		System.out.println("加载Spring配置文件完毕,Spring定时器成功启动!!!");
	}
}

        【0分下载示例资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿老高

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值