Spring内置任务调度实现添加、取消、重置

使用Spring的任务调度给我们的开发带来了极大的便利,不过当我们的任务调度配置完成后,很难再对其进行更改,除非停止服务器,修改配置,然后再重启,显然这样是不利于线上操作的,为了实现动态的任务调度修改,我在网上也查阅了一些资料,大部分都是基于quartz实现的,使用Spring内置的任务调度则少之又少,而且效果不理想,需要在下次任务执行后,新的配置才能生效,做不到立即生效。本着探索研究的原则,查看了一下Spring的源码,下面为大家提供一种Spring内置任务调度实现添加、取消、重置的方法。

首先,我们需要启用Spring的任务调度

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:task="http://www.springframework.org/schema/task"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.2.xsd">
   <task:annotation-driven executor="jobExecutor" scheduler="jobScheduler" />
   <task:executor id="jobExecutor" pool-size="5"/>
   <task:scheduler id="jobScheduler" pool-size="10" />
</beans>

这一部分配置在网上是很常见的,接下来我们需要联合使用@EnableSchedulingorg.springframework.scheduling.annotation.SchedulingConfigurer便携我们自己的调度配置,在SchedulingConfigurer接口中,需要实现一个void configureTasks(ScheduledTaskRegistrar taskRegistrar);方法,传统做法是在该方法中添加需要执行的调度信息。网上的基本撒谎那个也都是使用该方法实现的,使用addTriggerTask添加任务,并结合cron表达式动态修改调度时间,这里我们并不这样做。

查看一下ScheduledTaskRegistrar源码,我们发现该对象初始化完成后会执行scheduleTasks()方法,在该方法中添加任务调度信息,最终所有的任务信息都存放在名为scheduledFutures的集合中。

protected void scheduleTasks() {
        long now = System.currentTimeMillis();

        if (this.taskScheduler == null) {
            this.localExecutor = Executors.newSingleThreadScheduledExecutor();
            this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
        }
        if (this.triggerTasks != null) {
            for (TriggerTask task : this.triggerTasks) {
                this.scheduledFutures.add(this.taskScheduler.schedule(
                        task.getRunnable(), task.getTrigger()));
            }
        }
        if (this.cronTasks != null) {
            for (CronTask task : this.cronTasks) {
                this.scheduledFutures.add(this.taskScheduler.schedule(
                        task.getRunnable(), task.getTrigger()));
            }
        }
        if (this.fixedRateTasks != null) {
            for (IntervalTask task : this.fixedRateTasks) {
                if (task.getInitialDelay() > 0) {
                    Date startTime = new Date(now + task.getInitialDelay());
                    this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
                            task.getRunnable(), startTime, task.getInterval()));
                }
                else {
                    this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
                            task.getRunnable(), task.getInterval()));
                }
            }
        }
        if (this.fixedDelayTasks != null) {
            for (IntervalTask task : this.fixedDelayTasks) {
                if (task.getInitialDelay() > 0) {
                    Date startTime = new Date(now + task.getInitialDelay());
                    this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
                            task.getRunnable(), startTime, task.getInterval()));
                }
                else {
                    this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
                            task.getRunnable(), task.getInterval()));
                }
            }
        }
    }

所以我的思路就是动态修改该集合,实现任务调度的添加、取消、重置。实现代码如下:

package com.jianggujin.web.util.job;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;

import com.jianggujin.web.util.BeanUtils;

/**
 * 默认任务调度配置
 * 
 * @author jianggujin
 *
 */
@EnableScheduling
public class DefaultSchedulingConfigurer implements SchedulingConfigurer
{
   private final String FIELD_SCHEDULED_FUTURES = "scheduledFutures";
   private ScheduledTaskRegistrar taskRegistrar;
   private Set<ScheduledFuture<?>> scheduledFutures = null;
   private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<String, ScheduledFuture<?>>();

   @Override
   public void configureTasks(ScheduledTaskRegistrar taskRegistrar)
   {
      this.taskRegistrar = taskRegistrar;
   }

   @SuppressWarnings("unchecked")
   private Set<ScheduledFuture<?>> getScheduledFutures()
   {
      if (scheduledFutures == null)
      {
         try
         {
            scheduledFutures = (Set<ScheduledFuture<?>>) BeanUtils.getProperty(taskRegistrar, FIELD_SCHEDULED_FUTURES);
         }
         catch (NoSuchFieldException e)
         {
            throw new SchedulingException("not found scheduledFutures field.");
         }
      }
      return scheduledFutures;
   }

   /**
    * 添加任务
    * 
    * @param taskId
    * @param triggerTask
    */
   public void addTriggerTask(String taskId, TriggerTask triggerTask)
   {
      if (taskFutures.containsKey(taskId))
      {
         throw new SchedulingException("the taskId[" + taskId + "] was added.");
      }
      TaskScheduler scheduler = taskRegistrar.getScheduler();
      ScheduledFuture<?> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());
      getScheduledFutures().add(future);
      taskFutures.put(taskId, future);
   }

   /**
    * 取消任务
    * 
    * @param taskId
    */
   public void cancelTriggerTask(String taskId)
   {
      ScheduledFuture<?> future = taskFutures.get(taskId);
      if (future != null)
      {
         future.cancel(true);
      }
      taskFutures.remove(taskId);
      getScheduledFutures().remove(future);
   }

   /**
    * 重置任务
    * 
    * @param taskId
    * @param triggerTask
    */
   public void resetTriggerTask(String taskId, TriggerTask triggerTask)
   {
      cancelTriggerTask(taskId);
      addTriggerTask(taskId, triggerTask);
   }

   /**
    * 任务编号
    * 
    * @return
    */
   public Set<String> taskIds()
   {
      return taskFutures.keySet();
   }

   /**
    * 是否存在任务
    * 
    * @param taskId
    * @return
    */
   public boolean hasTask(String taskId)
   {
      return this.taskFutures.containsKey(taskId);
   }

   /**
    * 任务调度是否已经初始化完成
    * 
    * @return
    */
   public boolean inited()
   {
      return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;
   }
}

其中用到的BeanUtils源码如下:

package com.jianggujin.web.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtils
{

   public static Field findField(Class<?> clazz, String name)
   {
      try
      {
         return clazz.getField(name);
      }
      catch (NoSuchFieldException ex)
      {
         return findDeclaredField(clazz, name);
      }
   }

   public static Field findDeclaredField(Class<?> clazz, String name)
   {
      try
      {
         return clazz.getDeclaredField(name);
      }
      catch (NoSuchFieldException ex)
      {
         if (clazz.getSuperclass() != null)
         {
            return findDeclaredField(clazz.getSuperclass(), name);
         }
         return null;
      }
   }

   public static Method findMethod(Class<?> clazz, String methodName, Class<?>... paramTypes)
   {
      try
      {
         return clazz.getMethod(methodName, paramTypes);
      }
      catch (NoSuchMethodException ex)
      {
         return findDeclaredMethod(clazz, methodName, paramTypes);
      }
   }

   public static Method findDeclaredMethod(Class<?> clazz, String methodName, Class<?>... paramTypes)
   {
      try
      {
         return clazz.getDeclaredMethod(methodName, paramTypes);
      }
      catch (NoSuchMethodException ex)
      {
         if (clazz.getSuperclass() != null)
         {
            return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes);
         }
         return null;
      }
   }

   public static Object getProperty(Object obj, String name) throws NoSuchFieldException
   {
      Object value = null;
      Field field = findField(obj.getClass(), name);
      if (field == null)
      {
         throw new NoSuchFieldException("no such field [" + name + "]");
      }
      boolean accessible = field.isAccessible();
      field.setAccessible(true);
      try
      {
         value = field.get(obj);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
      field.setAccessible(accessible);
      return value;
   }

   public static void setProperty(Object obj, String name, Object value) throws NoSuchFieldException
   {
      Field field = findField(obj.getClass(), name);
      if (field == null)
      {
         throw new NoSuchFieldException("no such field [" + name + "]");
      }
      boolean accessible = field.isAccessible();
      field.setAccessible(true);
      try
      {
         field.set(obj, value);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
      field.setAccessible(accessible);
   }

   public static Map<String, Object> obj2Map(Object obj, Map<String, Object> map)
   {
      if (map == null)
      {
         map = new HashMap<String, Object>();
      }
      if (obj != null)
      {
         try
         {
            Class<?> clazz = obj.getClass();
            do
            {
               Field[] fields = clazz.getDeclaredFields();
               for (Field field : fields)
               {
                  int mod = field.getModifiers();
                  if (Modifier.isStatic(mod))
                  {
                     continue;
                  }
                  boolean accessible = field.isAccessible();
                  field.setAccessible(true);
                  map.put(field.getName(), field.get(obj));
                  field.setAccessible(accessible);
               }
               clazz = clazz.getSuperclass();
            } while (clazz != null);
         }
         catch (Exception e)
         {
            throw new RuntimeException(e);
         }
      }
      return map;
   }

   /**
    * 获得父类集合,包含当前class
    * 
    * @param clazz
    * @return
    */
   public static List<Class<?>> getSuperclassList(Class<?> clazz)
   {
      List<Class<?>> clazzes = new ArrayList<Class<?>>(3);
      clazzes.add(clazz);
      clazz = clazz.getSuperclass();
      while (clazz != null)
      {
         clazzes.add(clazz);
         clazz = clazz.getSuperclass();
      }
      return Collections.unmodifiableList(clazzes);
   }
}

因为加载的延迟,在使用这种方法自定义配置任务调度是,首先需要调用inited()方法判断是否初始化完成,否则可能出现错误。

接下来我们来测试一下:

package com.jianggujin.zft.job;

import java.util.Calendar;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.jianggujin.web.util.job.DefaultSchedulingConfigurer;

public class TestJob implements InitializingBean
{
   @Autowired
   private DefaultSchedulingConfigurer defaultSchedulingConfigurer;

   public void afterPropertiesSet() throws Exception
   {
      new Thread() {
         public void run()
         {

            try
            {
               // 等待任务调度初始化完成
               while (!defaultSchedulingConfigurer.inited())
               {
                  Thread.sleep(100);
               }
            }
            catch (InterruptedException e)
            {
               e.printStackTrace();
            }
            System.out.println("任务调度初始化完成,添加任务");
            defaultSchedulingConfigurer.addTriggerTask("task", new TriggerTask(new Runnable() {

               @Override
               public void run()
               {
                  System.out.println("run job..." + Calendar.getInstance().get(Calendar.SECOND));

               }
            }, new CronTrigger("0/5 * * * * ? ")));
         };
      }.start();
      new Thread() {
         public void run()
         {

            try
            {
               Thread.sleep(30000);
            }
            catch (Exception e)
            {
            }
            System.out.println("重置任务............");
            defaultSchedulingConfigurer.resetTriggerTask("task", new TriggerTask(new Runnable() {

               @Override
               public void run()
               {
                  System.out.println("run job..." + Calendar.getInstance().get(Calendar.SECOND));

               }
            }, new CronTrigger("0/10 * * * * ? ")));
         };
      }.start();
   }
}

在该类中,我们首先使用一个线程,等待我们自己的任务调度初始化完成后向其中添加一个每五秒钟打印一句话的任务,然后再用另一个线程过30秒后修改该任务,修改的本质其实是现将原来的任务取消,然后再添加一个新的任务。

在配置文件中初始化上面的类

<bean id="defaultSchedulingConfigurer" class="com.jianggujin.web.util.job.DefaultSchedulingConfigurer"/>
<bean id="testJob" class="com.jianggujin.zft.job.TestJob"/>

运行程序,观察控制台输出

这里写图片描述

这样我们就实现了动态的重置任务了。以上为个人探索出来的方法,如有更好的解决方案,欢迎指正。

  • 14
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
基于xxl-job改造,支持1.6jdk。改分布式任务调度特性如下: 1、简单:支持通过Web页面对任务进行CRUD操作,操作简单,一分钟上手; 2、动态:支持动态修改任务状态、暂停/恢复任务,以及终止运行中任务,即时生效; 3、调度中心HA(中心式):调度采用中心式设计,“调度中心”基于集群Quartz实现,可保证调度中心HA; 4、执行器HA(分布式):任务分布式执行,任务"执行器"支持集群部署,可保证任务执行HA; 5、任务Failover:执行器集群部署时,任务路由策略选择"故障转移"情况下调度失败时将会平滑切换执行器进行Failover; 6、一致性:“调度中心”通过DB锁保证集群分布式调度的一致性, 一次任务调度只会触发一次执行; 7、自定义任务参数:支持在线配置调度任务入参,即时生效; 8、调度线程池:调度系统多线程触发调度运行,确保调度精确执行,不被堵塞; 9、弹性扩容缩容:一旦有新执行器机器上线或者下线,下次调度时将会重新分配任务; 10、邮件报警:任务失败时支持邮件报警,支持配置多邮件地址群发报警邮件; 11、状态监控:支持实时监控任务进度; 12、Rolling执行日志:支持在线查看调度结果,并且支持以Rolling方式实时查看执行器输出的完整的执行日志; 13、GLUE:提供Web IDE,支持在线开发任务逻辑代码,动态发布,实时编译生效,省略部署上线的过程。支持30个版本的历史版本回溯。 14、数据加密:调度中心和执行器之间的通讯进行数据加密,提升调度信息安全性; 15、任务依赖:支持配置子任务依赖,当父任务执行结束且执行成功后将会主动触发一次子任务的执行, 多个子任务用逗号分隔;
Spring Boot提供了一种简单而强大的方式来实现定时任务调度。下面是使用Spring Boot实现定时任务调度的步骤: 1. 添加依赖:在`pom.xml`文件中添加Spring Boot的定时任务依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` 2. 创建定时任务类:创建一个继承自`QuartzJobBean`的定时任务类,并实现`executeInternal`方法,该方法中编写具体的定时任务逻辑。 ```java import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class MyJob extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // 定时任务逻辑 System.out.println("定时任务执行中..."); } } ``` 3. 配置定时任务:在`application.properties`或`application.yml`文件中配置定时任务的相关属性,例如触发时间、触发频率等。 ```yaml spring: quartz: job-store-type: memory properties: org: quartz: scheduler: instanceName: MyScheduler instanceId: AUTO job-details: my-job: cron: 0/5 * * * * ? job-class-name: com.example.MyJob ``` 4. 启动定时任务:在Spring Boot的启动类上添加`@EnableScheduling`注解,开启定时任务的自动配置。 ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 运行定时任务:启动Spring Boot应用程序后,定时任务将按照配置的触发时间和频率执行。 以上就是使用Spring Boot实现定时任务调度的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值