本文將告訴你如何使用spring的任務調度。主要使用@Scheduled註解
<!-- more -->java
須要會使用maven
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.xxz</groupId> <artifactId>scheduled-task-test</artifactId> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
package org.xxz.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) public void now() { log.info("The time is now {}", new Date()); } }
@Scheduled有三種類型參數fixedRate, fixedDelay, cronspring
fixedRate 表示每隔多少毫秒執行一次apache
fixedDelay 表示任務執行完成後隔多少毫秒執行一次maven
cron 定時任務表達式spring-boot
package org.xxz; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class); } }
cd scheduled-task-test mvn clean package java -jar target/scheduled-task-test-1.0.jar
擴展知識:若是不想使用spring的任務調度,可使用jdk自帶的任務調度類ui
ScheduledExecutorService#schedulecode
ScheduledExecutorService#scheduleAtFixedRatexml
ScheduledExecutorService#scheduleWithFixedDelayblog
今天的分享就到這裏了。謝謝閱讀。ip