美文网首页
Spring boot 动态的配置Scheduling

Spring boot 动态的配置Scheduling

作者: 我想起个好名字 | 来源:发表于2018-08-19 17:49 被阅读0次

    一:springboot配置静态定时任务

    1:pom中添加依赖

    2:启动类中加入@EnableScheduling来开启定时任务

    3:@Scheduled(cron = "0/10* * * * ?")// 每过10秒执行一次

    二: springboot动态配置定时任务:主要动态的配置。

    package com.example.demo.config;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.lang.Nullable;

    import org.springframework.scheduling.Trigger;

    import org.springframework.scheduling.TriggerContext;

    import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

    import org.springframework.scheduling.support.CronTrigger;

    import org.springframework.stereotype.Component;

    import java.text.SimpleDateFormat;

    import java.util.Date;

    import java.util.concurrent.ScheduledFuture;

    @Component

    @Configuration

    public class DynamicSchedulingConfig {

    @Autowired

        private ThreadPoolTaskSchedulerthreadPoolTaskScheduler;

        @Bean

        public ThreadPoolTaskSchedulerthreadPoolTaskScheduler(){

    return new ThreadPoolTaskScheduler();

        }

    private ScheduledFuturefuture;

        private Stringcron ="";

        public StringgetCron() {

    return cron;

        }

    public void setCron(String cron) {

    this.cron = cron;

            stopCron();

            future =threadPoolTaskScheduler.schedule(new Runnable() {

    @Override

                  public void run() {

    try {

    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                      }catch (Exception e) {

    e.printStackTrace();

                      }

    }

    }, new Trigger() {

    @Nullable

    @Override

                  public DatenextExecutionTime(TriggerContext triggerContext) {

    if("".equals(cron)||cron==null){

    return null;

                      }

    CronTrigger cronTrigger =new CronTrigger(cron);

                      Date nextExeDate = cronTrigger.nextExecutionTime(triggerContext);

                      return nextExeDate;

                  }

    });

        }

    public void stopCron(){

    if(future!=null){

    future.cancel(true);

            }

    }

    }

    相关文章

      网友评论

          本文标题:Spring boot 动态的配置Scheduling

          本文链接:https://www.haomeiwen.com/subject/vfaciftx.html