spring boot定时任务
1、在IDEA上创建一个springboot工程(示例是使用maven管理jar)
2、在pom.xml中添加jar包的地址
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
3、改造项目启动类加注解(@EnableScheduling)
package com.demo.timing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling @SpringBootApplication public class TimingApplication { public static void main(String[] args) { SpringApplication.run(TimingApplication.class, args); } }
4、编写任务接口
(1)正则表达式实现
package com.demo.timing.core; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TimingTask01 { private int count=0; @Scheduled(cron = "*/6 * * * * ?") private void pr(){ System.out.println("this is running"+count++); } }
(2)每隔定长时间执行任务(起好项目立刻执行一次)
@Component public class TimigTask02 { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("现在时间:" + dateFormat.format(new Date())); } }
5、执行结果
纸上得来终觉浅,绝知此事要躬行。