项目有个简单的小需求就是在考试时间结束后把待考的用户状态修改为缺考,可以利用TimerTask来实现,在java中实现定时执行任务的功能,主要用到Timer和TimerTask类。其中Timer是用来在一个后台线程按指定的计划来执行指定的任务。
在新增考试的时候添加一个定时任务:
// 添加执行任务(延迟 xxx秒执行,)
timer.schedule(timerTask,(timestamp-(epochSecond*1000)));
public void performTimerTask(Long timestamp,Long id){long epochSecond = LocalDateTime.now().atZone(ZoneId.of("Asia/Shanghai")).toInstant().getEpochSecond();TimerTask timerTask = new TimerTask() {@Overridepublic void run() {//获取参考人员记录列表,将待考修改为缺考List<ExamRecordVo> examRecordVos=examRecordBiz.getExamRecordList(id);for (int i = 0; i <examRecordVos.size() ; i++) {//修改用户考试状态ExamRecordVo recordVo = examRecordVos.get(i);if(recordVo.getStatus()==ExamStatusEnum.WAIT.getCode()){//待考ExamRecord examRecord =new ExamRecord();examRecord.setId(recordVo.getRecordId());examRecord.setStatus(ExamStatusEnum.ABSENT.getCode());//缺考examRecordBiz.update(examRecord);}}}};Timer timer = new Timer();timer.schedule(timerTask,(timestamp-(epochSecond*1000)));}