SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用。Cron表达式是一个字符串,包括6~7个时间元素,在SpringTask中可以用于指定任务的执行时间。
在线生成Cron表达式
业务场景说明:
用户对某商品进行下单操作,系统需要根据用户购买的商品信息生成订单并锁定商品的库存,系统设置了60分钟用户不付款就会取消订单,开启一个定时任务,每隔10分钟检查下,如果有超时还未付款的订单,就取消订单并取消锁定的商品库存。当然我们也可以用MQ实现延迟消息的方式来实现超时取消订单。
1.在配置类中添加一个@EnableScheduling注解即可开启SpringTask的定时任务能力
mport org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 定时任务配置
*/
@Configuration
@EnableScheduling
public class SpringTaskConfig {
}
2.添加OrderTimeOutCancelTask来执行定时任务
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 订单超时取消并解锁库存的定时器
*/
@Component
public class OrderTimeOutCancelTask {
private Logger LOGGER = LoggerFactory.getLogger(OrderTimeOutCancelTask.class);
/**
* cron表达式:Seconds Minutes Hours DayofMonth Month DayofWeek [Year]
* 每10分钟扫描一次,扫描设定超时时间之前下的订单,如果没支付则取消该订单
*/
@Scheduled(cron = "0 0/10 * ? * ?")
private void cancelTimeOutOrder() {
// 此处调用取消订单的方法,
LOGGER.info("取消订单,并根据sku编号释放锁定库存");
}
}
评论