现在有一张会议表,其中字段有开始时间和结束时间,现在需要定时任务,每过几个小时处理一次,判断当前时间是否大于结束时间,如果大于,对表相关的状态字段进行处理。上代码:
@Scheduled(cron = "0 0 9,12,16 * * ?")
public void cleanOutTimeMeeting2() {
System.out.println("开始清除");
List<MeetRoom> list = this.list();
list.stream().forEach(meetRoom -> {
String endTime = meetRoom.getEndTime();
if (StrUtil.isNotEmpty(endTime)) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date end = format.parse(endTime);
Date now = new Date();
int compare = end.compareTo(now);
if (compare < 0) {
meetRoom.setMeetingName("");
meetRoom.setStartTime("");
meetRoom.setEndTime("");
meetRoom.setNum(0);
meetRoom.setStatus(0);
}
this.updateById(meetRoom);
} catch (ParseException error) {
error.printStackTrace();
}
}
} ) ;
System.out.println("清除完毕");
}
首先获得整个表的list,然后通过Stream获得每一个记录,再取得每一个记录的结束时间endTime,此时为字符串类型,使用SimpleDateFormat将其转换为Date类型的end,使用new Date获得当前时间的Date类型的对象now,再end.compareTo(now);,结果为1,则end时间大于当前时间,结果为-1,当前时间大于end时间。
cron表达式如下: