Spring Boot 的定时任务,实现定时删除,缓存中,已经翻译完成超过24小时的文件
public class ScheduledTask {
//从yaml配置文件中获取time值 ,time可以随便设置多少, 此时time被设置24
@Value("${trans-reserve-time.time}")
private int time;
/**
* 定时任务,翻译完成后,如果翻译完成时间大于time时删除,time在配置文件中可配置
*/
//设置定时任务的 定时时间 该表达式表示,每天的0点开始执行任务
@Scheduled(cron = "0 0 0 * * ? ")
public void deleteTransFile(){
//工具类,获取缓存中的文件对象。
Map<String, DocumentTransBo> allFileInfo = DocumentTransInfoUtils.getAllFileInfo();
if (CollectionUtil.isNotEmpty(allFileInfo)){
for (String key:allFileInfo.keySet()){
DocumentTransBo documentTransBo = allFileInfo.get(key);
//判断翻译状态,4为翻译完成,如果不是4,直接break
if (documentTransBo.getTransStatus()!=4){
break;
}
//将documtTransBo对象中翻译完成时间转换为毫秒数
long transDoneTime = documentTransBo.getTransDoneTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant().toEpochMilli();
//判断(当前时间-减去文章翻译完成时的时间)除以3600000是将毫秒数转为小时
//time=24 >24说明是大于等于24小时,>=24的话(System.currentTimeMillis()-transDoneTime)/3600000需要+1
if ((System.currentTimeMillis()-transDoneTime)/3600000>time){
//调用一个自写工具类,调用的方法是 将该对象从缓存中移除
DocumentTransInfoUtils.deleteFilePathDocumentTransBo(documentTransBo.getFileUuid());
}
}
}
}
}
定时任务,cron的在线工具https://tool.lu/crontab/
https://tool.lu/crontab/ 点击上方跳转