@Configuration
public class QuartzConfig {
//定义任务详情
@Bean
public JobDetail orderjobDetail() {
//指定job的名称和持久化保存任务
return JobBuilder
.newJob(OrderQuartz.class) //1.自定义任务
.withIdentity("orderQuartz") //2.任务名称
.storeDurably()
.build();
}
//定义触发器
@Bean
public Trigger orderTrigger() {
/*SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInMinutes(1) //定义时间周期
.repeatForever();*/
CronScheduleBuilder scheduleBuilder
= CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"); //1.执行周期
return TriggerBuilder
.newTrigger()
.forJob(orderjobDetail())
.withIdentity("orderQuartz") //2.任务
.withSchedule(scheduleBuilder).build();
}
}
//准备订单定时任务
@Component
public class OrderQuartz extends QuartzJobBean{
@Autowired
private OrderMapper orderMapper;
/**
* 超时:当前时间 - 创建订单的时间> 30分钟
* 创建时间 < 当前时间-30分钟
*
* 业务:如果超时30分钟.则将状态由1改为6
* sql: update tb_order set status=6,updated=#{date}
* where status = 1 and created < #{timeOut}
*/
@Override
@Transactional
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
//1.计算超时时间 日历工具API 用于计算时间
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -30);
Date timeOut = calendar.getTime(); //获取超时时间
Order orderTemp = new Order();
orderTemp.setStatus(6).setUpdated(new Date());
UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("status", 1)
.lt("created", timeOut);
orderMapper.update(orderTemp, updateWrapper);
System.out.println("定时任务操成功!!!!!");
}
}