Springboot实现定时任务

2年前 (2022) 程序员胖胖胖虎阿
294 0 0
package com.yt.common.util;

import com.yt.exam.biz.ExamPlanBiz;
import com.yt.exam.biz.ExamRecordBiz;
import com.yt.exam.ctrl.vo.ExamRecordVo;
import com.yt.exam.entity.ExamPlan;
import com.yt.exam.entity.ExamRecord;
import com.yt.exam.enums.ExamStatusEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
public class SaticScheduleTask implements ApplicationContextAware {

    @Autowired
    @SuppressWarnings("all")
    private  ExamPlanBiz examPlanBiz;

    @Autowired
    @SuppressWarnings("all")
    private ExamRecordBiz examRecordBiz;

    //3.添加定时任务每分钟执行
    @Scheduled(cron = "0 */1 * * * ?")
    private  void configureTasks() {
        //从数据库获取
        List<ExamPlan> examPlans = examPlanBiz.loadAll();
        long epochSecond = LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai")).toInstant().getEpochSecond()*1000;
        for (int i = 0; i <examPlans.size() ; i++) {
            ExamPlan examPlan = examPlans.get(i);
            if(epochSecond >= examPlan.getEndTime().getTime()){
                 List<ExamRecordVo> examRecordVos=examRecordBiz.getExamRecordList(examPlan.getId());
                for (int j = 0; j <examRecordVos.size() ; j++) {
                    //修改用户考试状态
                    ExamRecordVo recordVo = examRecordVos.get(j);
                    if(recordVo.getStatus()== ExamStatusEnum.WAIT.getCode()){//待考
                        ExamRecord examRecord =new ExamRecord();
                        examRecord.setId(recordVo.getRecordId());
                        examRecord.setStatus(ExamStatusEnum.ABSENT.getCode());//缺考
                        examRecordBiz.update(examRecord);
                    }
                }
             }
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    }

}

版权声明:程序员胖胖胖虎阿 发表于 2022年11月11日 上午9:24。
转载请注明:Springboot实现定时任务 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...