SpringBoot中怎么動態(tài)控制定時任務(wù),相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
??稻W(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,保康網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為??登в嗉姨峁┢髽I(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的??底鼍W(wǎng)站的公司定做!
1.定時任務(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: 定時任務(wù)配置類 * @author: CaoTing * @date: 2019/5/23 **/@Configurationpublic class SchedulingConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); // 定時任務(wù)執(zhí)行線程池核心線程數(shù) taskScheduler.setPoolSize(4); taskScheduler.setRemoveOnCancelPolicy(true); taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-"); return taskScheduler; }}
2.定時任務(wù)注冊類:CronTaskRegistrar
這個類包含了新增定時任務(wù),移除定時任務(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: 添加定時任務(wù)注冊類,用來增加、刪除定時任務(wù)。 * @author: CaoTing * @date: 2019/5/23 **/@Componentpublic class CronTaskRegistrar implements DisposableBean { private final Map
3.定時任務(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: 定時任務(wù)運行類 * @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("定時任務(wù)開始執(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("定時任務(wù)執(zhí)行異常 - bean:%s,方法:%s,參數(shù):%s ", beanName, methodName, params), ex); } long times = System.currentTimeMillis() - startTime; logger.info("定時任務(wù)執(zhí)行結(jié)束 - bean:{},方法:{},參數(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.定時任務(wù)控制類:ScheduledTask
import java.util.concurrent.ScheduledFuture;/** * @program: simple-demo * @description: 定時任務(wù)控制類 * @author: CaoTing * @date: 2019/5/23 **/public final class ScheduledTask { public volatile ScheduledFuture> future; /** * 取消定時任務(wù) */ public void cancel() { ScheduledFuture> future = this.future; if (future != null) { future.cancel(true); } }}
5.定時任務(wù)的測試
編寫一個需要用于測試的任務(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ù)"); }}
進行單元測試
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: 測試定時任務(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 **/@Componentpublic 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; } //通過name獲取 Bean. public static Object getBean(String name) { return getApplicationContext().getBean(name); } //通過class獲取Bean. public static
7.我的pom依賴
看完上述內(nèi)容,你們掌握SpringBoot中怎么動態(tài)控制定時任務(wù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!