`

SpringMVC注解——@Scheduled 定时任务

 
阅读更多
Spring Task 定时任务 http://my.oschina.net/giegie/blog/490378


参考:在Spring中使用注解(@Scheduled)创建计划任务http://my.oschina.net/tinglanrmb32/blog/489125
原文:http://zwdsmileface.iteye.com/blog/2201238
也许以前框架经常使用quartz框架执行定时调度问题,但是现在我们介绍一下Spring给我们提供的@Scheduled定时任务。
    要使用此特性,需要Spring3.2以上版本
    如何去使用?下面我们用一个例子来介绍一下:
    1、在xml的配置中,需要加入:
     http://www.springframework.org/schema/task
     http://www.springframework.org/schema/task/spring-task-3.2.xsd"

   2、我们的task任务扫描注解
     <task:annotation-driven/>  
    我的配置扫描位置是: 
    <context:annotation-config/>  
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
    <--扫描你的任务所在的包 --> 
    <context:component-scan base-package="com.test"/> 

   3、写一个简单的例子:
   import org.springframework.context.annotation.Lazy; 
   import org.springframework.scheduling.annotation.Scheduled; 
   import org.springframework.stereotype.Component; 

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

   
   @Component 
   @Lazy(false) 
   public class TestJob { 
        public static SimpleDateFormat sdf_yyyyMMddHHmmss = new                  SimpleDateFormat("yyyyMMddHHmmss"); 


    @Scheduled(cron = "0/5 * * * * ?") 
    public void exejob() { 
        System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :执行中。。。"); 
       } 
    } 

    这样,一个简单的定时任务就完成了。
   注意(很重要):
    1、spring的@Scheduled注解  需要写在实现上、
    2、 定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true)
    3、实现类上要有组件的注解@Component
    关于corn表达式,最好是将cron表达式写在一个配置文件中,方便修改
  
CRON表达式  含义
    "0 0 12 * * ?"   每天中午十二点触发
    "0 15 10 ? * *"   每天早上10:15触发
    "0 15 10 * * ?"   每天早上10:15触发
    "0 15 10 * * ? *"  每天早上10:15触发
    "0 15 10 * * ? 2005"  2005年的每天早上10:15触发
    "0 * 14 * * ?"   每天从下午2点开始到2点59分每分钟一次触发
    "0 0/5 14 * * ?"  每天从下午2点开始到2:55分结束每5分钟一次触发
    "0 0/5 14,18 * * ?"  每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
    "0 0-5 14 * * ?"   每天14:00至14:05每分钟一次触发
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
"0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics