首先是pom.xml依賴:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springboot.samples</groupId> <artifactId>SpringBoot_Cron</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringBoot_Cron Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies> <build> <finalName>SpringBoot_Cron</finalName> </build> </project>
然后是定時任務類ScheduledTask:
package hello; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private Integer count0 = 1; private Integer count1 = 1; private Integer count2 = 1; @Scheduled(fixedRate = 5000) //fixedRate = 5000表示每隔5000ms,Spring scheduling會調用一次該方法,不論該方法的執行時間是多少 public void reportCurrentTime() throws InterruptedException { System.out.println(String.format("---第%s次執行,當前時間為:%s", count0++, dateFormat.format(new Date()))); } @Scheduled(fixedDelay = 10000) //fixedDelay = 5000表示當方法執行完畢5000ms后,Spring scheduling會再次調用該方法 public void reportCurrentTimeAfterSleep() throws InterruptedException { System.out.println(String.format("===第%s次執行,當前時間為:%s", count1++, dateFormat.format(new Date()))); } @Scheduled(cron = "*/15 * * * * *") //cron = "*/5 * * * * * *"提供了一種通用的定時任務表達式,這里表示每隔5秒執行一次 public void reportCurrentTimeCron() throws InterruptedException { System.out.println(String.format("+++第%s次執行,當前時間為:%s", count2++, dateFormat.format(new Date()))); } }
cron表達式的規則:
*/15 * * * * * 從左至右依次為:分鍾(0-59)、小時(1-23)、日期(1-31)、月份(1-12)、星期(0-6,0表示周日)
*/15表示分鍾間隔15執行一次即15s執行一次,cron詳細介紹猛戳:http://www.manpagez.com/man/5/crontab/
最后是Spring Boot啟動類:
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }