本来没啥好记的,但因为自己在使用过程中搜到cron表达式写错的影响,自己代码有bug的影响,错误以为scheduled没有生效,徒劳浪费时间。因此,在这里将类似配置都记载下来。
pom.xml:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zhen</groupId> <artifactId>scheduled-test</artifactId> <version>0.0.1-SNAPSHOT</version> <name>scheduled-test</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
启动类:
package com.zhen.scheduledtest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author zhen */ @SpringBootApplication @EnableScheduling public class ScheduledTestApplication { public static void main(String[] args) { SpringApplication.run(ScheduledTestApplication.class, args); } }
测试task:
package com.zhen.scheduledtest.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author zhen */ @Component public class TestTask { /** * 每分钟30s 执行一次打印 */ @Scheduled(cron = "30 * * * * ? ") public void doPrint(){ System.out.println("----------------"); } }