使用注解@Configuration
@EnableScheduling 定时任务注解
@Async异步注解
@Scheduled(cron = "0/5 * * * * ? ")定时任务执行
每天都执行一次,如果命中条件
package com.tsit.ertai.web.core.config;
import com.tsit.common.core.domain.entity.RecoverFootageEntity;
import com.tsit.system.domain.dto.RecoverFootageDTO;
import com.tsit.system.service.RecoverFootageService;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 手动回采的定时任务
*/
@Async
@Component
@Configuration
@EnableScheduling
public class RecoverScheduled {
@Resource
private RecoverFootageService recoverFootageService;
@Scheduled(cron = "0/5 * * * * ? ")
// @Scheduled(cron = "0 0 0 * * ? ")
public void recoveryFootageScheduled() {
//获取当前日期
Date date = new Date();
//将时间格式化成yyyy-MM-dd HH:mm:ss的格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//创建Calendar实例
Calendar cal = Calendar.getInstance();
//设置当前时间
cal.setTime(date);
//减去一天的方法:
cal.add(Calendar.DATE, -1);
String format1 = format.format(cal.getTime());
String format2 = format.format(date);
System.out.println(format1);
System.out.println(format2);
try {
Long startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format1).getTime();
Long endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format2).getTime();
List<RecoverFootageEntity> recoverFootageEntities = recoverFootageService.queryCurrentDay(startTime, endTime);
//判断集合是否为空,为空就新增一条数据
//TODO 新增的是哪个工作面数据
if (CollectionUtils.isEmpty(recoverFootageEntities)) {
RecoverFootageDTO recoverFootageDTO = new RecoverFootageDTO();
recoverFootageDTO.setFlag("1");//未填写的数据
recoverFootageDTO.setCreateTime(System.currentTimeMillis()*1000-3600*1000);//精确到毫秒
recoverFootageDTO.setMiningTime(System.currentTimeMillis()*1000-3600*1000);
recoverFootageDTO.setMiningPace(BigDecimal.ZERO);
recoverFootageDTO.setFaceId(5000l);
recoverFootageService.insert(recoverFootageDTO);
System.out.println("当天为查到数据,新增成功");
}
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("定时任务开始=============");
}
}
2 @Scheduled从配置文件读取时间,且执行不玩,不会执行下个执行计划
@Scheduled(fixedDelayString = "#{${scheduled.time}*1000}")