亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot實(shí)現(xiàn)動(dòng)態(tài)控制定時(shí)任務(wù)支持多參數(shù)功能

 更新時(shí)間:2019年05月31日 14:18:27   作者:連理枝  
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)動(dòng)態(tài)控制定時(shí)任務(wù)-支持多參數(shù)功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

由于工作上的原因,需要進(jìn)行定時(shí)任務(wù)的動(dòng)態(tài)增刪改查,網(wǎng)上大部分資料都是整合quertz框架實(shí)現(xiàn)的。本人查閱了一些資料,發(fā)現(xiàn)springBoot本身就支持實(shí)現(xiàn)定時(shí)任務(wù)的動(dòng)態(tài)控制。并進(jìn)行改進(jìn),現(xiàn)支持任意多參數(shù)定時(shí)任務(wù)配置

實(shí)現(xiàn)結(jié)果如下圖所示:

 

后臺(tái)測(cè)試顯示如下:

 

github 簡(jiǎn)單demo地址如下:

springboot-dynamic-task

1.定時(shí)任務(wù)的配置類:SchedulingConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
 * @program: simple-demo
 * @description: 定時(shí)任務(wù)配置類
 * @author: CaoTing
 * @date: 2019/5/23
 **/
@Configuration
public class SchedulingConfig {
  @Bean
  public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    // 定時(shí)任務(wù)執(zhí)行線程池核心線程數(shù)
    taskScheduler.setPoolSize(4);
    taskScheduler.setRemoveOnCancelPolicy(true);
    taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
    return taskScheduler;
  }
}

2.定時(shí)任務(wù)注冊(cè)類:CronTaskRegistrar

這個(gè)類包含了新增定時(shí)任務(wù),移除定時(shí)任務(wù)等等核心功能方法

import com.caotinging.demo.task.ScheduledTask;
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;
/**
 * @program: simple-demo
 * @description: 添加定時(shí)任務(wù)注冊(cè)類,用來(lái)增加、刪除定時(shí)任務(wù)。
 * @author: CaoTing
 * @date: 2019/5/23
 **/
@Component
public class CronTaskRegistrar implements DisposableBean {
  private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
  @Autowired
  private TaskScheduler taskScheduler;
  public TaskScheduler getScheduler() {
    return this.taskScheduler;
  }
  /**
   * 新增定時(shí)任務(wù)
   * @param task
   * @param cronExpression
   */
  public void addCronTask(Runnable task, String cronExpression) {
    addCronTask(new CronTask(task, cronExpression));
  }
  public void addCronTask(CronTask cronTask) {
    if (cronTask != null) {
      Runnable task = cronTask.getRunnable();
      if (this.scheduledTasks.containsKey(task)) {
        removeCronTask(task);
      }
      this.scheduledTasks.put(task, scheduleCronTask(cronTask));
    }
  }
  /**
   * 移除定時(shí)任務(wù)
   * @param task
   */
  public void removeCronTask(Runnable task) {
    ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
    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;
  }
  @Override
  public void destroy() {
    for (ScheduledTask task : this.scheduledTasks.values()) {
      task.cancel();
    }
    this.scheduledTasks.clear();
  }
}

3.定時(shí)任務(wù)執(zhí)行類:SchedulingRunnable

import com.caotinging.demo.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.Objects;
/**
 * @program: simple-demo
 * @description: 定時(shí)任務(wù)運(yùn)行類
 * @author: CaoTing
 * @date: 2019/5/23
 **/
public class SchedulingRunnable implements Runnable {
  private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class);
  private String beanName;
  private String methodName;
  private Object[] params;
  public SchedulingRunnable(String beanName, String methodName) {
    this(beanName, methodName, null);
  }
  public SchedulingRunnable(String beanName, String methodName, Object...params ) {
    this.beanName = beanName;
    this.methodName = methodName;
    this.params = params;
  }
  @Override
  public void run() {
    logger.info("定時(shí)任務(wù)開(kāi)始執(zhí)行 - bean:{},方法:{},參數(shù):{}", beanName, methodName, params);
    long startTime = System.currentTimeMillis();
    try {
      Object target = SpringContextUtils.getBean(beanName);
      Method method = null;
      if (null != params && params.length > 0) {
        Class<?>[] paramCls = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
          paramCls[i] = params[i].getClass();
        }
        method = target.getClass().getDeclaredMethod(methodName, paramCls);
      } else {
        method = target.getClass().getDeclaredMethod(methodName);
      }
      ReflectionUtils.makeAccessible(method);
      if (null != params && params.length > 0) {
        method.invoke(target, params);
      } else {
        method.invoke(target);
      }
    } catch (Exception ex) {
      logger.error(String.format("定時(shí)任務(wù)執(zhí)行異常 - bean:%s,方法:%s,參數(shù):%s ", beanName, methodName, params), ex);
    }
    long times = System.currentTimeMillis() - startTime;
    logger.info("定時(shí)任務(wù)執(zhí)行結(jié)束 - bean:{},方法:{},參數(shù):{},耗時(shí):{} 毫秒", beanName, methodName, params, times);
  }
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    SchedulingRunnable that = (SchedulingRunnable) o;
    if (params == null) {
      return beanName.equals(that.beanName) &&
          methodName.equals(that.methodName) &&
          that.params == null;
    }
    return beanName.equals(that.beanName) &&
        methodName.equals(that.methodName) &&
        params.equals(that.params);
  }
  @Override
  public int hashCode() {
    if (params == null) {
      return Objects.hash(beanName, methodName);
    }
    return Objects.hash(beanName, methodName, params);
  }
}

4.定時(shí)任務(wù)控制類:ScheduledTask

import java.util.concurrent.ScheduledFuture;
/**
 * @program: simple-demo
 * @description: 定時(shí)任務(wù)控制類
 * @author: CaoTing
 * @date: 2019/5/23
 **/
public final class ScheduledTask {
  public volatile ScheduledFuture<?> future;
  /**
   * 取消定時(shí)任務(wù)
   */
  public void cancel() {
    ScheduledFuture<?> future = this.future;
    if (future != null) {
      future.cancel(true);
    }
  }
}

5.定時(shí)任務(wù)的測(cè)試

編寫一個(gè)需要用于測(cè)試的任務(wù)類

import org.springframework.stereotype.Component;
/**
 * @program: simple-demo
 * @description:
 * @author: CaoTing
 * @date: 2019/5/23
 **/
@Component("demoTask")
public class DemoTask {
  public void taskWithParams(String param1, Integer param2) {
    System.out.println("這是有參示例任務(wù):" + param1 + param2);
  }
  public void taskNoParams() {
    System.out.println("這是無(wú)參示例任務(wù)");
  }
}

進(jìn)行單元測(cè)試

import com.caotinging.demo.application.DynamicTaskApplication;
import com.caotinging.demo.application.SchedulingRunnable;
import com.caotinging.demo.config.CronTaskRegistrar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * @program: simple-demo
 * @description: 測(cè)試定時(shí)任務(wù)
 * @author: CaoTing
 * @date: 2019/5/23
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DynamicTaskApplication.class)
public class TaskTest {
  @Autowired
  CronTaskRegistrar cronTaskRegistrar;
  @Test
  public void testTask() throws InterruptedException {
    SchedulingRunnable task = new SchedulingRunnable("demoTask", "taskNoParams", null);
    cronTaskRegistrar.addCronTask(task, "0/10 * * * * ?");
    // 便于觀察
    Thread.sleep(3000000);
  }
  @Test
  public void testHaveParamsTask() throws InterruptedException {
    SchedulingRunnable task = new SchedulingRunnable("demoTask", "taskWithParams", "haha", 23);
    cronTaskRegistrar.addCronTask(task, "0/10 * * * * ?");
    // 便于觀察
    Thread.sleep(3000000);
  }
}

6.工具類:SpringContextUtils

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * @program: simple-demo
 * @description: spring獲取bean工具類
 * @author: CaoTing
 * @date: 2019/5/23
 **/
@Component
public class SpringContextUtils implements ApplicationContextAware {
  private static ApplicationContext applicationContext = null;
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (SpringContextUtils.applicationContext == null) {
      SpringContextUtils.applicationContext = applicationContext;
    }
  }
  //獲取applicationContext
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
  //通過(guò)name獲取 Bean.
  public static Object getBean(String name) {
    return getApplicationContext().getBean(name);
  }
  //通過(guò)class獲取Bean.
  public static <T> T getBean(Class<T> clazz) {
    return getApplicationContext().getBean(clazz);
  }
  //通過(guò)name,以及Clazz返回指定的Bean
  public static <T> T getBean(String name, Class<T> clazz) {
    return getApplicationContext().getBean(name, clazz);
  }
}

7.我的pom依賴

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatisplus-spring-boot-starter</artifactId>
      <version>1.0.5</version>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>2.1.9</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 數(shù)據(jù)庫(kù)-->
    <!--<dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>-->
    <!-- https://mvnrepository.com/artifact/com.hynnet/oracle-driver-ojdbc -->
    <!--<dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>-->
    <!-- 單元測(cè)試 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>provided</scope>
    </dependency>
    <!--redisTemplate -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.3</version>
    </dependency>
    <!-- http連接 restTemplate -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
    </dependency>
    <!-- 工具-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.31</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google/guava -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>10.0.1</version>
    </dependency>
    <!-- pinyin4j -->
    <dependency>
      <groupId>com.belerweb</groupId>
      <artifactId>pinyin4j</artifactId>
      <version>2.5.0</version>
    </dependency>
  </dependencies>

    8.總結(jié)

建議移步github獲取簡(jiǎn)單demo上手實(shí)踐哦,在本文文首哦。有幫助的話點(diǎn)個(gè)贊吧,筆芯。

以上所述是小編給大家介紹的SpringBoot實(shí)現(xiàn)動(dòng)態(tài)控制定時(shí)任務(wù)支持多參數(shù)功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Java注解Annotation與自定義注解詳解

    Java注解Annotation與自定義注解詳解

    本文全面講述了Java注解Annotation與Java自定義注解及相關(guān)內(nèi)容,大家可以認(rèn)真看看
    2018-03-03
  • 詳解Java的Hibernate框架中的set映射集與SortedSet映射

    詳解Java的Hibernate框架中的set映射集與SortedSet映射

    這篇文章主要介紹了詳解Java的Hibernate框架中的set映射集與SortedSet映射,Hibernate是Java的SSH三大web開(kāi)發(fā)框架之一,需要的朋友可以參考下
    2015-12-12
  • SpringBoot中各個(gè)層級(jí)結(jié)構(gòu)的具體實(shí)現(xiàn)

    SpringBoot中各個(gè)層級(jí)結(jié)構(gòu)的具體實(shí)現(xiàn)

    在SpringBoot項(xiàng)目中,常常會(huì)把代碼文件放入不同的包中,本文主要介紹了SpringBoot中各個(gè)層級(jí)結(jié)構(gòu)的具體實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-05-05
  • 如何用java編寫一個(gè)rmi

    如何用java編寫一個(gè)rmi

    RMI能讓一個(gè)Java程序去調(diào)用網(wǎng)絡(luò)中另一臺(tái)計(jì)算機(jī)的Java對(duì)象的方法,那么調(diào)用的效果就像是在本機(jī)上調(diào)用一樣。下面我們來(lái)詳細(xì)了解一下吧
    2019-06-06
  • hotspot解析jdk1.8?Unsafe類park和unpark方法使用

    hotspot解析jdk1.8?Unsafe類park和unpark方法使用

    這篇文章主要為大家介紹了hotspot解析jdk1.8?Unsafe類park和unpark方法使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • Java實(shí)現(xiàn)世界上最快的排序算法Timsort的示例代碼

    Java實(shí)現(xiàn)世界上最快的排序算法Timsort的示例代碼

    Timsort?是一個(gè)混合、穩(wěn)定的排序算法,簡(jiǎn)單來(lái)說(shuō)就是歸并排序和二分插入排序算法的混合體,號(hào)稱世界上最好的排序算法。本文將詳解Timsort算法是定義與實(shí)現(xiàn),需要的可以參考一下
    2022-07-07
  • 如何使用Collections.reverse對(duì)list集合進(jìn)行降序排序

    如何使用Collections.reverse對(duì)list集合進(jìn)行降序排序

    這篇文章主要介紹了Java使用Collections.reverse對(duì)list集合進(jìn)行降序排序,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Spring核心容器IOC原理實(shí)例解析

    Spring核心容器IOC原理實(shí)例解析

    這篇文章主要介紹了Spring核心容器IOC原理實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Java實(shí)現(xiàn)銀行ATM系統(tǒng)

    Java實(shí)現(xiàn)銀行ATM系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)銀行ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • Maven統(tǒng)一版本管理的實(shí)現(xiàn)

    Maven統(tǒng)一版本管理的實(shí)現(xiàn)

    在使用Maven多模塊結(jié)構(gòu)工程時(shí),配置版本是一個(gè)比較頭疼的事,本文主要介紹了Maven統(tǒng)一版本管理的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-03-03

最新評(píng)論