spring boot: 定时任务处理订单(spring boot v2.5.4)
一,配置文件:
application.yml#profile
#database
spring:
profiles:
active: cron
说明:指定profile为cron,
如果项目在多台机器上部署时, 只有指定为cron时定时任务才生效说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,java代码
task/OrderTask.java@Profile("cron”) //profiles.active指定为cron时才生效
@Configuration //用于标记配置类
@EnableScheduling // 开启定时任务
public class OrderTask {
//日志类
private static final Logger loggerTask = LogManager.getLogger("TaskLog");
//读取配置文件的类,此处不是必需
@Resource
private ConfigBeanValue configBeanValue;
//时间间隔,例如:5秒
//@Scheduled(cron = "0/5 * * * * ?”)
//或直接指定时间间隔,例如:5秒
//@Scheduled(fixedRate=5000)
//时间间隔,10分
@Scheduled(cron = "0 0/10 * * * ?")
@Async
public void orderTasks() {
System.err.println("执行订单定时任务时间: " + LocalDateTime.now());
loggerTask.info("执行订单定时任务开始");
System.out.println("isOrderEnabled:"+configBeanValue.isOrderEnabled);
}
}
三,测试效果
查看控制台输出:四,查看spring boot版本:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.4)