import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.xiaoqinmucao.model.entity.back.SysSchedule;
import com.xiaoqinmucao.util.AssertException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* 添加定时任务注册类,用来增加、删除定时任务。
*
* @author Luck
*/
@Component
public class CronTaskRegistrar implements DisposableBean {
private final Map<Long, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
@Autowired
private TaskScheduler taskScheduler;
public void addCronTask(SysSchedule schedule) {
try {
Class<?> clazz = Class.forName(schedule.getClassName());
Method method = ReflectUtil.getMethodByName(clazz, schedule.getMethodName());
if (BooleanUtil.isFalse(schedule.getStatus())) {
return;
}
this.addCronTask(schedule.getId(), () -> {
Object bean = SpringUtil.getBean(clazz);
ReflectUtil.invoke(bean, method);
}, schedule.getCron());
} catch (ClassNotFoundException e) {
AssertException.error(e.getMessage());
}
}
public void addCronTask(Long scheduleId, Runnable task, String cronExpression) {
addCronTask(scheduleId, new CronTask(task, cronExpression));
}
public void addCronTask(Long scheduleId, CronTask cronTask) {
if (cronTask != null) {
if (this.scheduledTasks.containsKey(scheduleId)) {
removeCronTask(scheduleId);
}
this.scheduledTasks.put(scheduleId, scheduleCronTask(cronTask));
}
}
public void removeCronTask(Long scheduleId) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(scheduleId);
if (scheduledTask != null) {
scheduledTask.cancel();
}
}
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
ScheduledFuture<?> scheduledFuture = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
scheduledTask.setScheduledFuture(scheduledFuture);
return scheduledTask;
}
@Override
public void destroy() {
for (ScheduledTask task : this.scheduledTasks.values()) {
task.cancel();
}
this.scheduledTasks.clear();
}
}
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoqinmucao.model.entity.back.SysSchedule;
import com.xiaoqinmucao.service.back.ISysScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author Luck
* @date 2022/10/19:21:15
*/
@Slf4j
@Configuration
@Order
public class DynamicScheduleConfig implements ApplicationRunner {
@Autowired
private CronTaskRegistrar taskRegistrar;
@Autowired
private ISysScheduleService sysScheduleService;
@Bean
public ThreadPoolTaskScheduler scheduledExecutorService() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
scheduler.setThreadNamePrefix("xqmc-task-");
//设置任务注册器的调度器
scheduler.setRemoveOnCancelPolicy(true);
return scheduler;
}
@Override
public void run(ApplicationArguments args) throws Exception {
List<SysSchedule> sysSchedules = sysScheduleService.list(
new LambdaQueryWrapper<SysSchedule>()
.eq(SysSchedule::getIsDeleted, false)
.eq(SysSchedule::getStatus, true));
for (SysSchedule schedule : sysSchedules) {
taskRegistrar.addCronTask(schedule);
}
}
}
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.xiaoqinmucao.anno.Scheduled;
import com.xiaoqinmucao.config.CustomerProperties;
import com.xiaoqinmucao.model.entity.back.SysSchedule;
import com.xiaoqinmucao.service.back.ISysScheduleService;
import com.xiaoqinmucao.util.AssertException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author Luck
* @date 2022/12/12:19:13
*/
@Slf4j
@Component
@Transactional
public class ScheduleInitializer implements ApplicationRunner {
@Autowired
private CustomerProperties customerProperties;
@Autowired
private ISysScheduleService sysScheduleService;
@Override
public void run(ApplicationArguments args) throws Exception {
List<SysSchedule> schedules = sysScheduleService.list(new LambdaQueryWrapper<SysSchedule>().eq(SysSchedule::getIsDeleted, false));
if (CollUtil.isNotEmpty(schedules)) {
log.info("已存在定时任务,无需初始化任务");
return;
}
List<String> taskPackage = customerProperties.getTaskPackage();
if (CollUtil.isEmpty(taskPackage)) {
return;
}
Set<Class<?>> classes = CollUtil.newHashSet();
for (String packageName : taskPackage) {
Set<Class<?>> cls = ClassUtil.scanPackage(packageName, clazz -> Arrays.stream(clazz.getDeclaredMethods()).anyMatch(m -> m.isAnnotationPresent(Scheduled.class)));
if (CollUtil.isEmpty(cls)) {
continue;
}
classes.addAll(cls);
}
List<SysSchedule> sysSchedules = CollUtil.newArrayList();
Set<Method> methods = classes.stream()
.flatMap(clazz -> Arrays.stream(clazz.getDeclaredMethods()))
.filter(method -> method.isAnnotationPresent(Scheduled.class))
.collect(Collectors.toSet());
// 用类名和方法名来去重
Map<String, Method> distinctMap = Maps.newHashMap();
for (Method method : methods) {
String className = method.getDeclaringClass().getName();
String methodName = method.getName();
String scheduleName = className + "#" + methodName;
AssertException.isTrue(distinctMap.containsKey(scheduleName), "{}中的{}重复,请修改", className, methodName);
distinctMap.put(scheduleName, method);
SysSchedule schedule = new SysSchedule();
schedule.setClassName(className);
schedule.setMethodName(methodName);
Scheduled scheduled = method.getAnnotation(Scheduled.class);
schedule.setScheduleName(scheduled.name());
schedule.setCron(scheduled.cron());
sysSchedules.add(schedule);
}
if (CollUtil.isNotEmpty(sysSchedules)) {
sysScheduleService.saveBatch(sysSchedules);
log.info("初始化{}个定时任务", sysSchedules.size());
}
}
}