码迷,mamicode.com
首页 > 编程语言 > 详细

使用spring自带定时器: @Scheduled

时间:2016-04-10 01:32:23      阅读:1233      评论:0      收藏:0      [点我收藏+]

标签:spring   定时   定时任务   定时器   scheduled   

项目开发中需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息之类的。平时使用Quartz比较多,但配置相对麻烦一点。今天就来说说Spring自带的定时任务。


Spring自带实现定时任务有两种方式,一种是通过注解的方式实现,一种是通过在配置文件中配置后实现。


一、通过spring的注解( @Scheduled)实现定时任务。

首先当然是Springde 配置:


第一步:添加这三段:

xmlns:task="http://www.springframework.org/schema/task

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd

技术分享


第二步:开启Spring定时器注解开关

<task:annotation-driven />  

技术分享


第三步:编写定时任务类和其中的方法,并为类和方法(可以有多个方法)添加注解。

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

import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("scheduledManager")
@Lazy(value=false)
public class ScheduledManager {
	public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	//任务一
	@Scheduled(cron = "0/5 * * * * ?")
	public void autoCardCalculate() {
	System.out.println(simpleDateFormat.format(new Date()) + " :执行中任务1……");
	}
	
	//任务二
	@Scheduled(cron = "0/5 * * * * ?")
	public void autoCardCalculate2() {
	System.out.println(simpleDateFormat.format(new Date()) + " :执行中任务2……");
	}
}



第四步:启动服务,效果立竿见影

技术分享

+++++++++++++++++++++++++++以上便是通过注解的方式实现定时任务的+++++++++++++++++++++++++


++++++++++++++++下面便是通过在spring配置文件中配置的方式实现定时任务+++++++++++++++++++++

二、通过spring的配置文件实现定时任务。

与注解方式不同的是,定时任务的时间控制不是在注解中控制的,而是在配置文件中控制。

即在spring的配置文件中配置下面这段,代码中就不需要 @Scheduled 这个注解了。

<task:scheduled-tasks scheduler="myScheduler">  
        <task:scheduled ref="scheduledManager" method="autoCardCalculate" cron="0/5 * * * * *"/>  
        <task:scheduled ref="scheduledManager" method="autoCardCalculate2" cron="1/5 * * * * *"/>  
    </task:scheduled-tasks>  
    <task:scheduler id="myScheduler" pool-size="10"/>

技术分享


唯一需要注意的就是定时任务类中的@Lazy(vlaue=false),这个注解,这个是懒加载的注解,可以不写,但是如果把value改为true,定时任务是不会执行的。因为加上之后,spring容器初始化的时候就不会触发这个定时任务了。




本文出自 “Simple Life” 博客,请务必保留此出处http://simplelife.blog.51cto.com/9954761/1762108

使用spring自带定时器: @Scheduled

标签:spring   定时   定时任务   定时器   scheduled   

原文地址:http://simplelife.blog.51cto.com/9954761/1762108

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!