一 點睛
從Spring3.1開始,計劃任務在Spring中的實作變得異常的簡單。隻需要下面兩步。
1 通過在配置類上注解@EnableScheduling來開啟對計劃任務的支援。
2 在要執行計劃任務的方法上注解@Scheduled,聲明這是一個計劃任務。
Spring通過@Scheduled支援多種類型的計劃任務,包含cron、fixDelay、fixRate等。
二 實戰
1 配置類
package com.wisely.highlight_spring4.ch3.taskscheduler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskscheduler")
@EnableScheduling //1
public class TaskSchedulerConfig {
}
2 計劃任務執行類
package com.wisely.highlight_spring4.ch3.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) //該方法是計劃任務,使用fixedRate屬性每隔固定時間執行。
public void reportCurrentTime() {
System.out.println("每隔五秒執行一次 " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 28 11 ? * *" ) //每天11點28分執行
public void fixTimeExecution(){
System.out.println("在指定時間 " + dateFormat.format(new Date())+"執行");
}
}
3 主類
package com.wisely.highlight_spring4.ch3.taskscheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
}
}
三 運作結果
每隔五秒執行一次 19:58:50
每隔五秒執行一次 19:58:55
每隔五秒執行一次 19:59:00
每隔五秒執行一次 19:59:05
每隔五秒執行一次 19:59:10
每隔五秒執行一次 19:59:15
每隔五秒執行一次 19:59:20
每隔五秒執行一次 19:59:25
每隔五秒執行一次 19:59:30
每隔五秒執行一次 19:59:35
每隔五秒執行一次 19:59:40
每隔五秒執行一次 19:59:45
每隔五秒執行一次 19:59:50
每隔五秒執行一次 19:59:55
每隔五秒執行一次 20:00:00
每隔五秒執行一次 20:00:05