0 Star 0 Fork 0

sylz/cron_tutorial

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
HelloSchedule.java 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
sylz 提交于 2020-09-29 02:13 . init
package org.nobody.mallb2c.mallseckill.scheduled;
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 java.util.concurrent.CompletableFuture;
/**
* @author [email protected]
* @create 2020-09-28-13:14
*/
@Slf4j
@Component
@EnableAsync //←开启异步任务功能
@EnableScheduling
public class HelloSchedule {
/** tip1
* Spring中只能写6位的cron表达式,不允许【年】*/
//Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method 'hello': Cron expression must consist of 6 fields (found 7 in "*/5 * * * * ? 2020")
//@Scheduled(cron = "*/5 * * * * ? 2020")
/** tip2
* Spring中周1就是1,周日就是7(不同于标准的cron)*/
/*@Scheduled(cron = "* * * ? * 1")
public void hello(){
log.info("hello...");
}*/
/** tip3
* 定时任务不应该阻塞,但spring中默认是阻塞的*/
/*@Scheduled(cron = "* * * ? * 1")
public void hello() throws InterruptedException {
log.info("hello...");
Thread.sleep(3000);
}*/
/** 解决方案①
* 让业务以异步的方式运行*/
/*@Scheduled(cron = "* * * ? * 1")
public void hello() throws InterruptedException {
log.info("hello...");
CompletableFuture.runAsync(()->{
xxxService.hello();
});
}*/
/** 解决方案②
* 让定时任务异步执行 @EnableAsync @Async
* 定时任务 自动配置类参看 TaskSchedulingAutoConfiguration
* 异步定时任务 自动配置类参看 TaskExecutionAutoConfiguration (也是靠的线程池实现的异步*/
@Async
@Scheduled(cron = "* * * ? * 1")
public void hello() throws InterruptedException {
log.info("hello...");
Thread.sleep(3000);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Vennasia/cron_tutorial.git
[email protected]:Vennasia/cron_tutorial.git
Vennasia
cron_tutorial
cron_tutorial
master

搜索帮助