1、pom.xml中導入必要的依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> </dependencies>
2、寫一個springboot的啟動類:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan(basePackages = { "com.xwj.tasks" }) @EnableScheduling // 開啟定時任務 @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
注意這里一定要加上@EnableScheduling注解,用於開啟定時任務
3、開始寫定時任務:
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduleTask { @Scheduled(fixedRate = 1000) // @Scheduled(cron = "0 23-25 18 * * ?") public void testSchedule() { System.out.println("定時任務:" + System.currentTimeMillis()); } }
解釋:
@Scheduled注解:
1、fixedRate 以固定速率執行。以上表示每隔1秒執行一次
2、fixedDelay 以上一個任務開始時間為基准,從上一任務開始執行后再次調用
3、cron表達式。可以實現定時調用,表達式具體配置可參考corn表達式——用於設置定時任
在使用的過程中,樓主覺得,如果只有一個定時任務,fixedRate與fixedDelay的效果是一樣一樣的