spring 注解方式配置定时任务

来源:互联网 发布:程序员在银行干什么 编辑:程序博客网 时间:2024/05/21 18:42

一、注解的方式
1:spring 配置文件中增加这句

<task:annotation-driven/>  

2:确保扫描程序能够扫描后 下面第3步骤的java类

<context:component-scan base-package="cms"/>  

3:AnnotationQuartz.java

package cms;  import base.util.BaseDateUtil;  import org.springframework.scheduling.annotation.Scheduled;  import org.springframework.stereotype.Component;  import java.util.Date;  @Component  public class AnnotationQuartz {      @Scheduled(cron = "0 0/1 15,* * * ?")      //需要注意@Scheduled这个注解,它可配置多个属性:cron\fixedDelay\fixedRate      public void test() {          String dateStr = BaseDateUtil.getFormatString(new Date(), "yyyy-MM-dd HH:mm:ss");          System.out.println("小说城 www.xiaoshuocity.com 每分钟执行一次:" + dateStr);      }  } 

二、不需要配置文件,只要加扫描就好
1:确保扫描程序能够扫描后 下面第3步骤的java类

<context:component-scan base-package="cms"/>  

2:AnnotationQuartz.java

package cms;  import base.util.BaseDateUtil;  import org.springframework.scheduling.annotation.Scheduled;  import org.springframework.stereotype.Component;  import java.util.Date;  @EnableScheduling@Component@Lazy(false) public class AnnotationQuartz {      @Scheduled(cron = "0 0/1 15,* * * ?")      //需要注意@Scheduled这个注解,它可配置多个属性:cron\fixedDelay\fixedRate      public void test() {          String dateStr = BaseDateUtil.getFormatString(new Date(), "yyyy-MM-dd HH:mm:ss");          System.out.println("小说城 www.xiaoshuocity.com 每分钟执行一次:" + dateStr);      }  }  

第三种用@EnableScheduling完美代替了配置。

0 0