动态定时任务

工具类


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.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CronTaskRegistrar implements DisposableBean {

    @Override
    public void destroy() throws Exception {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }

    private final Map<String, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    /**
     * 新增定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(String taskId,Runnable task, String cronExpression) {
        addCronTask(taskId,new CronTask(task, cronExpression));
    }

    public void addCronTask(String taskId,CronTask cronTask) {
        if (cronTask != null) {
            if (this.scheduledTasks.containsKey(taskId)) {
                removeCronTask(taskId);
            }

            this.scheduledTasks.put(taskId, scheduleCronTask(cronTask));
        }
    }

    /**
     * 移除定时任务
     */
    public void removeCronTask(String taskId) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(taskId);
        if (scheduledTask != null){
            scheduledTask.cancel();}
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());

        return scheduledTask;
    }

}

静态配置

import java.util.concurrent.ScheduledFuture;

public final class ScheduledTask {

    public volatile ScheduledFuture<?> future;
    /**
     * 取消定时任务
     */
    public void cancel() {
        ScheduledFuture<?> future = this.future;
        if (future != null) {
            future.cancel(true);
        }
    }

}

启动配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@EnableScheduling
@Configuration
public class SchedulingConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        // 创建任务调度线程池
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        // 初始化线程池数量
        taskScheduler.setPoolSize(5);
        // 是否将取消后的任务,从队列中删除
        taskScheduler.setRemoveOnCancelPolicy(true);
        // 设置线程名前缀
        taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
        return taskScheduler;
    }


}

代码

        //删除任务
        try {
            registrar.removeCronTask(taskId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //启动任务
        registrar.addCronTask(qo.getId(),doTask(entity),corn);

    private Runnable doTask(ScheduledConfigEntity entity) {
        task = new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                //todo
                //发送推送
  
            }
        };
        return task;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 动态定时任务通常是指在 Spring Boot 应用程序中实现的、可以在运行时动态添加、修改或删除的任务调度功能。这类功能允许开发者基于实际业务需求灵活地管理任务的执行时间间隔、周期和执行逻辑。 ### Spring Boot 中动态定时任务的实现 #### 依赖引入 为了支持动态定时任务,你需要引入 Spring Batch 或 Quartz 等框架的相关库。例如,如果你选择使用 Quartz,可以将以下 Maven 依赖添加到项目的 `pom.xml` 文件中: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> ``` #### 定义任务 首先,在 Spring Boot 的应用中定义一个用于执行任务的 Java 类,并使用 `@Tasklet` 或 `@StepScope` 注解标注任务类。同时,需要实现特定的功能,比如数据处理、更新状态等。 ```java import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; public class DynamicJob implements Tasklet { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { // 执行具体任务的操作... return RepeatStatus.FINISHED; } } ``` #### 配置调度器 在 Spring Boot 的配置文件中(通常是 `application.properties` 或 `application.yml`),设置 Quartz 集群和其他必要的属性,然后创建并启动 Quartz Scheduler。 ```properties # 配置 Quartz Scheduler spring.job.names=my-job # 设置任务名称 spring.batch.job.enabled=true # 启动批处理功能 quartz.scheduler.instanceName=INSTANCE_NAME # 集群实例名(如果使用集群) ``` #### 动态添加和删除任务 Spring Boot 和 Quartz 提供了通过 API 添加和删除任务的能力,这意味着你可以根据需要动态地控制哪些任务正在运行以及何时停止它们。这通常涉及到在应用程序中创建一个新的任务实例,然后将其注册到 Quartz Scheduler 上。 ```java ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Scheduler scheduler = (QuartzScheduler) context.getBean("quartzScheduler"); try { JobDetail job = JobBuilder.newJob(MyJob.class) .withIdentity("myJob", "group") .usingJobData("key", "value") .build(); Trigger trigger = TriggerBuilder.newTrigger() .forJob(job) .withIdentity("myTrigger", "group") .startNow() .withSchedule(CronScheduleBuilder.cronSchedule("0 0/5 * * * ?")) .build(); scheduler.scheduleJob(job, trigger); } catch (Exception e) { throw new RuntimeException(e); } // 删除任务同样涉及调度器的交互操作 scheduler.pauseTrigger(trigger.getKey()); scheduler.unscheduleJob(trigger.getKey()); scheduler.deleteJob(job.getKey()); ``` ### 使用示例 - 添加任务 假设我们希望在 Spring Boot 运行时添加一个定时任务,每五分钟执行一次,可以在主程序中执行以下代码: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); try { Scheduler scheduler = (QuartzScheduler) context.getBean("quartzScheduler"); // 根据需要调整 cron 表达式以满足特定需求 CronTrigger trigger = (CronTrigger) scheduler.getTriggersOfJob(JobKey.jobKey("myJob", "default")).iterator().next(); scheduler.rescheduleJob(trigger.getKey(), CronScheduleBuilder.cronSchedule("0/5 * * * * ?")); } catch (SchedulerException e) { throw new IllegalStateException("Failed to schedule job", e); } } } ``` ### 相关问题: 1. **如何监控和调试动态定时任务?** Spring Boot 和 Quartz 都提供了一定的监控工具和日志系统帮助开发者追踪任务的状态和错误。 2. **如何优化动态任务的性能和资源利用?** 正确设置任务调度频率、合理规划内存分配和优化任务执行效率都是关键点。 3. **在微服务架构下如何实现动态定时任务?** 可以考虑通过服务间通信(如 HTTP API 或消息队列)来协调各个服务中的定时任务,确保系统的高可用性和灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值