import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
public class SchedulerTask implements SchedulingConfigurer {
@Mapper
public interface CronMapper {
@Select("select * from access_work_shift_time")
List getCron();
}
@Autowired
@SuppressWarnings("all")
CronMapper cronMapper;
//记录日志
private Logger logger = LoggerFactory.getLogger(SchedulerTask.class);
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//获取定时任务执行信息
List tasks = getAllTasks(null);
if (tasks.size() > 0) {
for (int i = 0; i < tasks.size(); i++) {
try {
// 注册计时任务到Scheduling接口
taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)), getTrigger(tasks.get(i)));
} catch (Exception e) {
logger.error("定时任务启动错误:" + e.getMessage());
}
}
}
}
//从数据库里取得所有要执行的定时任务
private List getAllTasks(String id) {
List list = new ArrayList<>();
try {
list=cronMapper.CronMapper();
}catch (Exception e){
logger.error(e.getLocalizedMessage());
}
return list;
}
//执行业务逻辑
private Runnable getRunnable(AccessWorkShiftTimeVO SchedulerConfig) {
return new Runnable() {
@Override
public void run() {
//业务代码
}
};
}
//获取下次执行时间
public Trigger getTrigger(AccessWorkShiftTimeVO schedulerConfig) {
return new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
AccessWorkShiftTimeVO cpSyncCron = new AccessWorkShiftTimeVO();
cpSyncCron = getAllTasks(schedulerConfig.getId()).get(0);
String cron = "";
if (cpSyncCron != null) {
cron = cpSyncCron.getCron();
}
if (cron == null || "".equals(cron)) {
return null;
}
CronTrigger cronTrigger = new CronTrigger(cron);
Date nextExec = cronTrigger.nextExecutionTime(triggerContext);
return nextExec;
}
};
}
}