基于springboot ThreadPoolTaskScheduler类实现定时任务动态添加修改

需求:有不定个的定时任务模板需要创建,定时任务在运行过程中,激发时间等属性可能发生修改.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;


@Component
public class ScheduledVm {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    private ScheduledFuture<?> future;

    private int taskSchedulerCorePoolSize=50;

    static boolean isinitialized=false;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        threadPoolTaskScheduler=new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(taskSchedulerCorePoolSize);
	/**需要实例化线程*/
        threadPoolTaskScheduler.initialize();
        isinitialized=true;
        return threadPoolTaskScheduler;
    }

    /**每隔1小时重新扫描构建定时任务*/
@Scheduled(fixedDelay = 3600000) private void getCron() { /**每次重新获取任务模板的时候重构定时任务*/ try{ if (isinitialized) {
		/**设置为false,关闭线程池中的任务时,直接执行shutdownNow()*/
                threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(false);
                threadPoolTaskScheduler.shutdown();
        }catch (Exception e){
            
        }finally {
            threadPoolTaskScheduler();
        }

	
        List<Integer> types= new ArrayList<>();
 
	Integer period=1;
       
	/**根据不同的任务类型分别创建不同的任务,动态添加到线程池中*/
        for (Integer type: types) {
        
                if (type == 1) {

                    threadScheduler(new Runnable() {
                        @Override
                        public void run() {
                         System.out.println("类型:"+type);
                    },getCrons(startTime,period));
                } else if (type == 2){

                    threadScheduler(new Runnable() {
                        @Override
                        public void run() {                    
			System.out.println("类型:"+type);  
},getCrons(startTime,period)); } else if (type == 3){ threadScheduler(new Runnable() { @Override public void run() {
			System.out.println("类型:"+type); 
},getCrons(startTime,period));
} } }
 
	/**这种方式经过我的测试不能正常运行,每次重构任务池时都会把任务先执行一次*/

//    private ScheduledFuture<?> threadScheduler(Runnable runnable, Date startTime,long period){
//     
//        return future = threadPoolTaskScheduler.scheduleWithFixedDelay(runnable,startTime,period);
//    }


    /***使用cron表达式动态构建符合要求的表达式*/
    private String getCrons(Date date,Integer period)
    {
//        String ss="*";
//        String mm="*";
//        String hh="*";
        String dd="*";
        String MM="*";
        String yy="*";
        String []time=format.format(date).split("-");
        dd=time[2];
        MM=time[1];
        yy=time[0];
        /**每隔数月*/
        if (period==1||period==2)
        {
            MM=MM+"/"+period;
        }else if (period==7||period==14)
        {
            /**每隔数天*/
            dd=dd+"/"+period;
        }

	/**每隔数月时,表示,在yyyy-MM-dd 8:30:00时执行一次,然后每隔MM月再执行
	   每隔数天时,表示,再yyyy-MM-dd 8:30:00时执行一次,然后每隔dd天再执行*/
        return "0 30 8"+" "+dd+" "+MM+" ?"+yy;
    }

    private ScheduledFuture<?> threadScheduler(Runnable runnable, String cron){
        /**动态创建定时任务*/
        return future = threadPoolTaskScheduler.schedule(runnable, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                return new CronTrigger(cron).nextExecutionTime(triggerContext);
            }
        });//new CronTrigger("0/5 * * * * *")
    }



}



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值