有些业务场景需要根据开始时间把状态从未开始变成进行中,或者根据结束时间还未完成就变成未完成状态的,这就需要定时去开启一个新的线程处理这个逻辑。
/**
* 指定日期执行逻辑
* @param checkId
* @param date
* @param type
*/
public void addTask(Long checkId, Date date, int type) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
GoodsCheck goodsCheck = baseMapper.selectById(checkId);
if (type == 0 && "not_start".equals(goodsCheck.getStatus())){
goodsCheck.setStatus("in_review");
goodsCheck.setAppStatus("underway");
}else if (type == 1 && !"successful".equals(goodsCheck.getStatus())){
goodsCheck.setStatus("unfinished");
goodsCheck.setAppStatus("unfinished");
}
baseMapper.updateById(goodsCheck);
};
// 获取当前时间
long currentTime = System.currentTimeMillis();
// 设置指定时间
long milliseconds = date.getTime();
if (currentTime < milliseconds) {
// 计算时间差
long delay = (milliseconds - currentTime);
TimeUnit timeUnit = TimeUnit.MILLISECONDS;
executor.schedule(task, delay, timeUnit);
}
executor.shutdown();
}