1、定时任务的创建方式:
- 基于注解@Schedule和,定时任务执行时间较短,并且比较单一
2、@Schedule和@EnableScheduling
(1)在pom.xml中加入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency>
(2)在springboot的启动类DemoApplication上添加@EnableScheduling
package com.example.demo;
@SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.println("你好"); } }
(3)创建定时任务类
package com.example.demo.Time;
@Component public class timer { @Scheduled(cron = "0/15 * * * * ? ") //每隔15秒执行一次 private void test(){ System.out.println("任务开始时间:"+new Date()); } }
执行效果: