복붙노트

[SPRING] 스프링 스케쥴러가 cron 표현식을 동적으로 변경합니다.

SPRING

스프링 스케쥴러가 cron 표현식을 동적으로 변경합니다.

applicationContext.xml에 taskScheduler를 만들 수 있으며 cron 속성을 기반으로 주기적으로 작업이 트리거됩니다.

스케줄러가 시작된 후이 cron 표현식 (트리거링 기간)을 변경하고 싶습니다. JavaEE 애플리케이션이 실행되는 동안 말입니다.

3.XX를 사용하여

해결법

  1. ==============================

    1.사실 나는 똑같은 문제에 직면 해있다.

    사실 나는 똑같은 문제에 직면 해있다.

    나는 사용자로부터 날짜 (1-31), 시간, 요일, 스케줄러 유형 (매일, 매월, 매주)을 가져와야한다고 가정합니다.

    먼저 사용자로부터 주어진 날짜 시간에 cron 표현식을 생성해야합니다. 다음 코드는 cron 표현식을 생성하고 맵을 취하여 cron 표현식을 문자열로 반환합니다.

    public String  getCronExp(final Map<String, Object> configMap) {
    
        LOGGER.debug(">>  getCronExp");
    
        String exp = "";
    
        final String type = (String) configMap.get(SCHEDULER_TYPE);
        final String time = (String) configMap.get(TIME);
        final String[] split = time.split(this.COLON);
        String hour = split[0];
        String min = split[1];
    
        if ("00".equalsIgnoreCase(min)) {
            min = ZERO;
        }
        if ("00".equalsIgnoreCase(hour)) {
            hour = "0";
        }
        if ("daily".equalsIgnoreCase(type)) {
    
            exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE + this.ASTERISK
                    + this.WHITE_SPACE + "?";
    
        } else if ("monthly".equalsIgnoreCase(type)) {
            final String date = (String) configMap.get(START_DATE);
            exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + date + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE
                    + "?";
    
        } else if ("weekly".equalsIgnoreCase(type)) {
    
            final String dayOfWeek = (String) configMap.get(DAY_OF_WEEK);
    
            exp = this.ZERO + this.WHITE_SPACE + min + this.WHITE_SPACE + hour + this.WHITE_SPACE + "?" + this.WHITE_SPACE + this.ASTERISK + this.WHITE_SPACE
                    + dayOfWeek;
        }
    
        LOGGER.info("Latest cron  expression scheduler " + exp);
        LOGGER.debug("<<  getCronExp");
        return exp;
    }
    

    cron 표현식을 얻은 후에 스케줄러를 트리거하는 문제가 있습니다.

    runnable을 확장하는 클래스를 만듭니다.

    public  class Scheduler implements Runnable {
    
    @SuppressWarnings("rawtypes")
    ScheduledFuture scheduledFuture;
    
    TaskScheduler taskScheduler ;
    
    //this method will kill previous scheduler if exists and will create a new scheduler with given cron expression
    public  void reSchedule(String cronExpressionStr){
     if(taskScheduler== null){
            this.taskScheduler = new ConcurrentTaskScheduler();
        }
         if (this.scheduledFuture() != null) {
            this.scheduledFuture().cancel(true);
        }
     this.scheduledFuture = this.taskScheduler.schedule(this, new CronTrigger(cronExpressionStr));
    }
    
    @Override
    public  void run(){
    // task to be performed 
    }
    
    //if you want on application to read data on startup from db and schedule the schduler use following method
     @PostConstruct
      public void initializeScheduler() {
        //@postcontruct method will be called after creating all beans in application context
        // read user config map from db 
        // get cron expression created 
        this.reSchedule(cronExp);
      }
    
    }
    
  2. from https://stackoverflow.com/questions/20546403/spring-scheduler-change-cron-expression-dynamically by cc-by-sa and MIT license