spring 註解方式配置定時任務
阿新 • • 發佈:2019-02-20
一、註解的方式
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完美代替了配置。