手动实现Spring定时任务的增删改查(连接数据库的任务)

  •  动态表达式的任务注册表
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 lombok.Data;
    
    import java.util.concurrent.ScheduledFuture;
    
    /**
     * @author Luck
     */
    @Data
    public final class ScheduledTask {
    
        private volatile ScheduledFuture<?> scheduledFuture;
    
        /**
         * 取消定时任务
         */
        public void cancel() {
            ScheduledFuture<?> future = this.scheduledFuture;
            if (future != null) {
                future.cancel(true);
            }
        }
    }
    
  • 动态加载数据库中的配置的定时任务
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());
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值