ThreadPoolTaskScheduler-定时任务动态配置执行

需求:同一个定时任务,可能会在不同的时间去执行,人工可以配置

 @Component
public class TimerTaskDynamicCron implements InitializingBean {
	
	 private static Logger logger = LoggerFactory.getLogger(TimerTaskDynamicCron.class);
	 
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private RobotTimeTaskDao robotTimeTaskDao;
    
    private List> robotFutureList=new CopyOnWriteArrayList>();
 
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }
    
    /**
     * 项目启动时就运行的
        或者用 @PostConstruct 这个标签
     */
    @Override
	public void afterPropertiesSet() throws Exception {
    	List tasks = robotTimeTaskDao.findAll();
    	for(RobotTimeTask task:tasks){
    		startRobotTask(task);
    	}
	}
    
    /**
     * 开启定时任务
     * @param task
     */
    public void startRobotTask(RobotTimeTask task) {
    	ScheduledFuture future = threadPoolTaskScheduler.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("num::::::::"+task.getNum());
				logger.info("Task...........run..{}",task.getNum());
			}
		},new Trigger(){
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext){
            	//0/30 * * * * ?
            	CronTrigger trigger = new CronTrigger(task.getCron());
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    	robotFutureList.add(future);
    }
    
    /**
     * 停止定时任务
     */
    public void stopRobotTask() {
        for(ScheduledFuture future:robotFutureList){
        	if (future != null) {
                //不会马上停止任务,会等任务执行完 只是执行了interrupt方法
                future.cancel(true);
            }
        }
        robotFutureList.clear();
        logger.info("DynamicTask.stopTask()");
    }

}

模拟用户从前台修改定时:

@Service
public class TimerTaskDynamicService {
	 
	  @Autowired
	 private TimerTaskDynamicCron timerTaskDynamicCron;
	 
	 public void stopTask(){
        //先停止现有的定时
		 timerTaskDynamicCron.stopRobotTask();
		 
        //模拟新改的定时
		 List tasks=new ArrayList();
		 RobotTimeTask task1=new RobotTimeTask();
		 task1.setCron("0/5 * * * * ?");
		 task1.setNum(1);
		 
		 RobotTimeTask task2=new RobotTimeTask();
		 task2.setCron("0/10 * * * * ?");
		 task2.setNum(2);
		 
		 RobotTimeTask task3=new RobotTimeTask();
		 task3.setCron("0/15 * * * * ?");
		 task3.setNum(3);
		 
		 tasks.add(task1);tasks.add(task2);tasks.add(task3);
		 
		 for(RobotTimeTask task:tasks){
			 timerTaskDynamicCron.startRobotTask(task);
	     }
        //把旧的定时从数据库删除
        
        //再把新的task储存到数据库  以便下次启动时  执行到最新的任务

	 }

}

 

你可能感兴趣的:(spring)