文章目录
常见定时任务
1、动态创建定时任务推送运营类的消息(定时推送消息)
2、广告结算定时任务扫表找到对应的可结算记录(定时扫表更新状态)
3、每天定时更新数据记录(定时更新数据)
定时任务三种方式
使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:
1、基于注解(@Scheduled)
2、基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
3、基于注解设定多线程定时任务
1、基于 @Scheduled 注解
(1)@Configuration将该类标记为配置类,自动注入。
(2)@EnableScheduling 开启定时任务。
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class TaskBasedAnnotation {
// 每两秒执行一次
@Scheduled(cron = "*/2 * * * * ?")
public void sayHello(){
System.out.println("Hello!!!"+Thread.currentThread().getName());
}
}
注:
使用@Scheduled 注解很方便,但缺点是当我们调整了执行周期的时候,需要重启应用才能生效,这多少有些不方便。为了达到实时生效的效果,可以使用接口来完成定时任务。
2、基于接口(SchedulingConfigurer)
导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.0.4.RELEASE