spring任务调度

16 篇文章 0 订阅

方式一:Spring+quartz

配置方式如上一篇中提到的,这个是很完整的了,我已经测试过了

http://blog.csdn.net/qq_22585755/article/details/48246675


方式二: Spring + task

先写一个普通类,包括一个方法,将其注册为bean

import java.util.Date;
import org.springframework.stereotype.Component;
/**
 * 
 * @author TongYinLing
 */
@Component("testSchedule")
public class TestSchedule
{
	public void task(){
		System.out.println("cron!" + new Date().getTime());
	}
}


PS:如果在task方法上使用了@Schedule(cron="0/5 * * * * * "),此cron优先于配置xml中的


xml配置为:(由于我本地系统中还需要其他的配置,所以关于task的内容我重点标记出来了)

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        					http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      						http://www.springframework.org/schema/context
      						http://www.springframework.org/schema/context/spring-context-2.5.xsd
      						http://www.springframework.org/schema/tx
      						http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
      						http://www.springframework.org/schema/task 
      						http://www.springframework.org/schema/task/spring-task-3.0.xsd">  

	<!-- 添加注解驱动 -->
	<tx:annotation-driven />

	<!-- Spring定时器注解开关--> 
	<task:annotation-driven />

	<!-- 自动扫描的包名 -->  
        <context:component-scan base-package="*" />  

	<!-- 开启任务调度  -->
	<task:scheduled-tasks>
		<task:scheduled ref="testSchedule" method="task" cron="0/13 * * * * ?" />
	</task:scheduled-tasks> 
</beans>



方式三:Spring+@EnableScheduling

首先声明一个调度对象和执行方法

import java.util.Date;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 
 * @author TongYinLing
 */
@Configuration
@EnableScheduling
public class TestSchedule
{
	@Scheduled(cron="0/5 * * * * *")
	public void task(){
		System.out.println("testSchedule:" + new Date().getTime());
	}
}


关于EnableScheduling的用法可以参考:http://docs.spring.io/autorepo/docs/spring/3.2.0.M1/api/org/springframework/scheduling/annotation/EnableScheduling.html

文章中介绍说要另外声明一个AppConfig作为父级类,我觉得好像没必要,而且当有多个任务对象时,还要特意声明

还有在测试此方法时,发现方法会被调用两次,追其原因是由于applicationContext.xml文件被调用了两次


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值