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
public class SchedulerTask implements SchedulingConfigurer {
@Mapper
public interface CronMapper {
@Select("select * from access_work_shift_time")
List<AccessWorkShiftTimeVO> getCron();
}
@Autowired
@SuppressWarnings("all")
CronMapper cronMapper;
private Logger logger = LoggerFactory.getLogger(SchedulerTask.class);
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
List<AccessWorkShiftTimeVO> tasks = getAllTasks(null);
if (tasks.size() > 0) {
for (int i = 0; i < tasks.size(); i++) {
try {
taskRegistrar.addTriggerTask(getRunnable(tasks.get(i)), getTrigger(tasks.get(i)));
} catch (Exception e) {
logger.error("定时任务启动错误:" + e.getMessage());
}
}
}
}
private List<AccessWorkShiftTimeVO> getAllTasks(String id) {
List<AccessWorkShiftTimeVO> 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;
}
};
}
}