SpringBoot+schedule+可以动态添加或删除定时任务

基于注解模式

  1. 使用 @Scheduled(cron=“0 0 1 * * ?”) 注解(此处cron表达式为每天凌晨一点执行)
  2. 注意,使用此注解时,若不加 @Async 那么就会是单线程的,多任务时会阻塞,例如A任务1点执行,B任务1点10分执行,若A一直执行到1点10分,那么B任务就会被阻塞,不执行了。
  3. 上代码:
@SpringBootApplication
//开启定时
@EnableScheduling
@MapperScan(basePackages = { "com.XXX.XXX.maintenancecenter.mapper" })
public class StartApp {
	public static void main(String[] args) {
		SpringApplication.run(StartApp.class, args);
	}
}

@Component
//@Async
public class ScheduleTask{

    /**默认是fixedDelay 上一次执行完毕时间后执行下一轮*/
    @Scheduled(cron = "0/5 * * * * *")
    public void run() throws InterruptedException {
        Thread.sleep(6000);
        System.out.println(Thread.currentThread().getName()+"=====>>>>>使用cron  {}"+(System.currentTimeMillis()/1000));
    }

    /**fixedRate:上一次开始执行时间点之后5秒再执行*/
    @Scheduled(fixedRate = 5000)
    public void run1() throws InterruptedException {
        Thread.sleep(6000);
        System.out.println(Thread.currentThread().getName()+"=====>>>>>使用fixedRate  {}"+(System.currentTimeMillis()/1000));
    }

    /**fixedDelay:上一次执行完毕时间点之后5秒再执行*/
    @Scheduled(fixedDelay = 5000)
    public void run2() throws InterruptedException {
        Thread.sleep(7000);
        System.out.println(Thread.currentThread().getName()+"=====>>>>>使用fixedDelay  {}"+(System.currentTimeMillis()/1000));
    }

    /**第一次延迟2秒后执行,之后按fixedDelay的规则每5秒执行一次*/
    @Scheduled(initialDelay = 2000, fixedDelay = 5000)
    public void run3(){
        System.out.println(Thread.currentThread().getName()+"=====>>>>>使用initialDelay  {}"+(System.currentTimeMillis()/1000));
    }

基于接口的自定义线程模式

1.基于接口模式时,最重要的就是 SchedulingConfigurer ,自己定义线程池,不多说,直接上代码:


@Component
public class MyScheConfigurer implements SchedulingConfigurer {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private ScheduledTaskRegistrar taskRegistrar;

	private Set<ScheduledFuture<?>> scheduledFutures = null;

	private Map<String, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<String, ScheduledFuture<?>>();

	/** 每天凌晨1点执行 */
	@Value("${taskInfo.delTmpFile.delTmpFileCron}")
	String delTmpFileCron;

	/** 每天凌晨2点执行 */
	@Value("${taskInfo.clearTable.clearTableCron}")
	String clearTableCron;

	@Value("${taskInfo.clearTable.tableSchema}")
	String tableSchema;
	
	@Autowired
	MaintenanceCenterMapper dao;

	@Autowired
	MyScheConfigurer scheConfigurer;
	
	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
		logger.info("configureTasks");
		
		List<TsTableClearRule> sortClearRules = sortClearRules();
		
		this.taskRegistrar = scheduledTaskRegistrar;
		this.taskRegistrar.setTaskScheduler(TP.getScheduleTP(sortClearRules.size()+1));
		
		//每天凌晨1点执行的删除临时文件任务
		logger.info("delTmpFileCron = "+delTmpFileCron);
		scheConfigurer.addTriggerTask("DELTMPFILE:"+delTmpFileCron, new TriggerTask(new DelTmpFileTask(dao), getTriggerByCron(delTmpFileCron)));
				
		//每天凌晨2点执行的删除临时表数据的任务
		sortClearRules.forEach(rule->{
			logger.info("rule = "+rule.toString());
			scheConfigurer.addTriggerTask(rule.getRuleId(), new TriggerTask(new ClearTableTask(dao,tableSchema, rule), getTriggerByCron(rule.getOpearTime())));
		});
		
	}

	private Set<ScheduledFuture<?>> getScheduledFutures() {
		if (scheduledFutures == null) {
			try {
				scheduledFutures = (Set<ScheduledFuture<?>>) BeanUtils.getProperty(taskRegistrar,  "scheduledTasks");
			} 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;
	}

	/**
	 * 初始化数据库数据
	 * @return
	 */
	private  List<TsTableClearRule> sortClearRules() {
		List<TsTableClearRule> rules = dao.selectTsTableClearRule();
		rules.forEach(rule -> {
			//暂时按照固定值来做
//			if (StringUtils.isBlank(rule.getOpearTime())){
				logger.info("rule = "+rule.toString());
				rule.setOpearTime(clearTableCron);
//			}
		});
		return rules;
	}
	
	/**
	 * 通过cron表达式获取触发器
	 * @param cron
	 * @return
	 */
	private Trigger getTriggerByCron(String cron) {
		Trigger trigger = new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发,可修改任务的执行周期.
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		};
		return trigger;
	}
	
}
public class TP {
	/**
	 * 将queueSize=1,尽可能保持按任务提交顺序进行执行!
	 * 
	 * @param maximumPoolSize
	 *            线程池峰值线程个数
	 * @return ThreadPoolExecutor
	 */
	public static ThreadPoolExecutor getTP(int maximumPoolSize) {
		return (new ThreadPoolExecutor(maximumPoolSize / 10 + 1, maximumPoolSize, 2, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(1), new CallerRunsPolicy()));

		// return (new ThreadPoolExecutor(maxPoolSize , maxPoolSize, 0,
		// TimeUnit.SECONDS,
		// new ArrayBlockingQueue<Runnable>(maxPoolSize + 5), new
		// ThreadPoolExecutor.CallerRunsPolicy()));
	}

	/**
	 * 
	 * @param maximumPoolSize
	 *            线程池峰值线程个数
	 * @return ThreadPoolExecutor
	 */
	public static ThreadPoolTaskScheduler getScheduleTP(int maximumPoolSize) {
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(maximumPoolSize);
		taskScheduler.setThreadNamePrefix("TaskScheduler-ThreadPool-");
		// 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者
		taskScheduler.setRejectedExecutionHandler(new CallerRunsPolicy());
		// 调度器shutdown被调用时等待当前被调度的任务完成
		taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
		// 等待时长
		taskScheduler.setAwaitTerminationSeconds(60);
		taskScheduler.initialize();
		return taskScheduler;
	}

	/**
	 * 
	 * @param maximumPoolSize
	 *            线程池峰值线程个数
	 * @return ThreadPoolExecutor
	 */
	public static ThreadPoolTaskExecutor getExecutorTP(int maximumPoolSize) {
		ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
		taskExecutor.setCorePoolSize(maximumPoolSize / 10 + 1);
		taskExecutor.setMaxPoolSize(maximumPoolSize);
		taskExecutor.setThreadNamePrefix("TaskExecutor-ThreadPool-");
		// 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者
		taskExecutor.setRejectedExecutionHandler(new CallerRunsPolicy());
		// 调度器shutdown被调用时等待当前被调度的任务完成
		taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
		// 等待时长
		taskExecutor.setAwaitTerminationSeconds(60);
		taskExecutor.initialize();
		return taskExecutor;
	}

	
	/**
	 * @param maximumPoolSize
	 *            线程池峰值线程个数
	 * @param queueSize
	 *            线程池ArrayBlockingQueue大小
	 * @return ThreadPoolExecutor
	 */
	public static ThreadPoolExecutor getTP(int maximumPoolSize, int queueSize) {
		return (new ThreadPoolExecutor(maximumPoolSize / 10 + 1, maximumPoolSize, 2, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(queueSize), new CallerRunsPolicy()));
	}

	/**
	 * @param corePoolSize
	 *            线程池初始线程个数
	 * @param maximumPoolSize
	 *            线程池峰值线程个数
	 * @param queueSize
	 *            线程池ArrayBlockingQueue大小
	 * @return ThreadPoolExecutor
	 */
	public static ThreadPoolExecutor getTP(int corePoolSize, int maximumPoolSize, int queueSize) {
		return (new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 2, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(queueSize), new CallerRunsPolicy()));
	}

	/**
	 * A handler for rejected tasks that runs the rejected task directly in the
	 * calling thread of the {@code execute} method, unless the executor has
	 * been shut down, in which case the task is discarded.
	 */
	public static class CallerRunsPolicy implements RejectedExecutionHandler {
		/**
		 * Creates a {@code CallerRunsPolicy}.
		 */
		public CallerRunsPolicy() {
		}

		/**
		 * Executes task r in the caller's thread, unless the executor has been
		 * shut down, in which case the task is discarded.
		 * 
		 * @param r
		 *            the runnable task requested to be executed
		 * @param e
		 *            the executor attempting to execute this task
		 */
		public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
			try {
				e.getQueue().put(r);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			// if (!e.isShutdown()) {
			// r.run();
			// }
		}
	}

}
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);
	}
}

建议使用第二种方式,可以动态从数据库中获取cron,然后生成task任务,也可以动态关闭,添加,任务。

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Nicky_LC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值