1. 新建项目,在pom.xml导入必要的依赖。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 写一个SpringBoot的启动类
- 启动类里面使用@EnableScheduling 注解开启定时任务功能。
@SpringBootApplication
@EnableScheduling
@MapperScan("com.less.parent.dao")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
3. 编写定时任务
- 要在任务的类上写@Component,将当前的任务类注入到容器。
- 要在任务方法上写@Scheduled,然后编写cron表达式。
@Component
public class SchedulingTask {
@Scheduled(cron = "*/5 * * * * ?")
public void TestTask() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(new Date()));
}
}
4. 执行结果
2020-09-20 17:20:35
2020-09-20 17:20:40
2020-09-20 17:20:45
5. 总结
- fixedDelay和fixedRate,单位是毫秒,这里这里就是5秒和3秒,它们的区别就是:fixedRate就是每多次分钟一次,不论你业务执行花费了多少时间。我都是1分钟执行1次,而fixedDelay是当任务执行完毕后1分钟在执行。所以根据实际业务不同,我们会选择不同的方式。
- cron表达式:比如你要设置每天什么时候执行,就可以用它不会写的话,网上有专门的语法,可以单独去查。