Springboot定时任务开发
1.使用@EnableScheduling注解开启定时任务,
2.在需要定时执行的方法上添加@Scheduled(cron = "* * * * * ?")注解,
3.将定时任务放到Spring容器中进行管理 @Component
cron表达式,从左到右分别表示:秒 分 时 日 月 周
各个属性允许的值,参照下图
可通过在线cron表达式生成定时任务的时间
在线Cron表达式生成器
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 定时任务
* 1.@EnableScheduling 开启定时任务
* 2.@Scheduled 开启一个定时任务
*/
@EnableScheduling
@Slf4j
@Component
@EnableAsync
public class HelloSchedule {
@Resource
ThreadPoolExecutor threadPoolExecutor;
/**
* 1.spring中由6位组成,不包括第七位的年
* 2.在周几的位置,1~7表示周一到周日
* 3.定时任务不应该阻塞。默认是阻塞的
* 1)可以让其他业务的运行以异步的方式执行。即调用CompletableFuture.runAsync()方法解决
* 2)反过来,可以让定时任务以异步的方式执行
* a)在“类”上面添加注解: @EnableAsync
* b)给希望异步执行的方法上标注: @Async
* 解决:使用异步+定时任务来完成定时任务不阻塞
*/
@Async
@Scheduled(cron = "* * * * * ?")
public void hello(){
log.info("hello.....");
CompletableFuture.runAsync(()->{
//xxServiceImpl.doSomething()
},threadPoolExecutor);
}
}
上面的代码中在类名上使用@EnableAsync开启异步编程,在要异步执行的方法上使用@Async开启异步执行。