由于有一天是沒有更新部落格,導緻在部落格的書寫日期上面是一直晚一天的。
今天主要實戰的一些知識儲備羅列--計劃任務ScheduledTask
今天的定時任務是昨天的Spring aop應用的實際應用,廢話不多說,上代碼:
1,建立配置類,啟動注解的支援
package com.amarsoft.springboot.taskscheduler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("com.amarsoft.springboot.taskscheduler")
@EnableScheduling
public class TaskScheduledConfig {
}
2,建立計劃任務執行類
package com.amarsoft.springboot.taskscheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate=5000)
public void reportCurrentTime(){
System.out.println("每個五秒執行一次"+dateFormat.format(new Date()));
}
@Scheduled(cron="0 29 0 ? * *" )
public void fixTime(){
System.out.println("在指定的時間内"+dateFormat.format(new Date())+"執行任務");
}
}
代碼解釋:>1.通過@Scheduled聲明該方法是計劃任務,使用fixedRate屬性每個固定時間執行,機關是毫秒
>2.使用cron屬性可按照指定時間執行,此處是寫的每天的00:29:00執行,cron是unix和類unix系統下的定時任務
注意cron的配置: cron是設定定時執行的表達式
@Scheduled(cron="0 29 0 ? * *" )表示每天的00:29:00執行一次
@Scheduled(cron="0 0/5 * * * ?" )表示每隔五分鐘執行一次
zone表示執行時間的時區
FixedDelay 和fixedDelayString 表示一個固定延遲時間執行,上個任務完成後,延遲多長時間執行
fixedRate 和fixedRateString表示一個固定頻率執行,上個任務開始後,多長時間後開始執行
initialDelay 和initialDelayString表示一個初始延遲時間,第一次被調用前延遲的時間
3,測試運作
package com.amarsoft.springboot.taskscheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TaskScheduledApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskScheduledConfig.class);
}
}
4,執行結果: