基于 @Scheduled 注解的 ----定时任务
最常用的方法
@Scheduled 注解表示起开定时任务
依赖
<dependencies> <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>
在启动类上添加 这个注解即可自动开启任务
@EnableScheduling//开启定时任务
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling//开启定时任务 public class ScheduledApplication { public static void main(String[] args) { SpringApplication.run(ScheduledApplication.class, args); } }
任务类
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Date; @Component public class HelloComponent { /** * @Scheduled 注解表示起开定时任务 * * fixedDelay 属性表示下一个任务在本次任务执行结束 2000 ms 后开始 * fixedRate 表示下一个任务在本次任务开始 2000ms 之后开始 * initialDelay 表示启动延迟时间 */ @Scheduled(cron = "0/5 * * * * ?") public void hello() { System.out.println("hello:"+new Date()); } }
可以 动态的添加 schedul 任务
在任务类的方法上 添加
@Scheduled(cron = "${jobs.schedule}")
在配置文件 application.properties文件中 中添加
jobs.schedule = 0 0/45 * * * ?
作 者:一支会记忆的笔
---------------------
个性 签名:真正的学习不是记住知识,而是学会如何提出问题,研究问题,解决问题。
如果觉得这篇文章对你有小小的帮助的话,记得在下方“关注”哦,博主在此感谢!