SpringBoot 利用Timer 在指定时间2小时后执行任务

/**
 * @Description
 * @Author songwp
 * @Date 2022/8/5 12:51
 * @Version 1.0.0
 **/
@Component
public class SalaryDetailTask {

    protected Logger log = LoggerFactory.getLogger(SalaryDetailTask.class);

    @Autowired
    protected ISalaryDetailServiceExtend salaryDetailServiceExtend;

    /**
     * @param uploadId
     * @Date 2022/8/5 13:51
     * @Author songwp
     */
    public void TaskServiceImplExtend(String uploadId) {
        Calendar myDate = Calendar.getInstance();
        try {
            // 获取工资详情信息
            SalaryDetail salaryDetail = salaryDetailServiceExtend.lambdaQuery().eq(SalaryDetail::getRefUploadRecordId, uploadId).eq(SalaryDetail::getSendStatus, 1).list().get(0);
            // 获取发送时间
            myDate.setTime(salaryDetail.getSendTime());
            // 任务执行时间(发送时间的2小时之后)
            myDate.add(Calendar.HOUR, 2);
            Date afterOneMinute = myDate.getTime();
            log.info("Scheduled(执行器)在: afterOneMinute {}",afterOneMinute);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    salaryDetailServiceExtend.lambdaUpdate()
                            .set(SalaryDetail::getConfirmStatus,1)
                            .eq(SalaryDetail::getConfirmStatus,0)
                            .eq(SalaryDetail::getRefUploadRecordId,uploadId)
                            .eq(SalaryDetail::getSendStatus,1)
                            .update();
                    log.info("所属上传记录id:uploadId:{}--下的工资条信息确认状态,由 startStatus:{} --更新为--> endStatus :{} 成功!",uploadId,salaryDetail.getConfirmStatus(),1);
                }
            }, afterOneMinute);
        } catch (Exception e) {
            log.error("根据 uploadId:{} 未匹配到推送成功的工资详情信息,任务执行出现异常!",uploadId,e);
        }
    }
}
posted @ 2022-08-05 16:47  [奋斗]  阅读(358)  评论(0编辑  收藏  举报