본문 바로가기
Java

자바 Spring Boot 1.5 동적 Cron

by NaHyungMin 2023. 7. 19.

패키지와 클래스명, 인터페이스명 등은 정보 변경하느라 이상할수도 있음.

Bean 등록

@EnableScheduling
@Configuration
public class configuration {

  @Bean
  public ScheduledTaskRegistrar scheduledTaskRegistrar() {
    return new ScheduledTaskRegistrar();
  }
}

추상 클래스 ScheduledComponent

package ...

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledFuture;

@Component
public abstract class ScheduledComponent implements ApplicationContextAware, Ischeduled, BeanNameAware {
  private @Autowired ScheduledTaskRegistrar taskRegistrar;
  private ScheduledFuture<?> scheduledFuture;
  private ApplicationContext applicationContext;
  //private CronTask cronTask;
  private String beanName;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

 /* @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.addCronTask(cronTask);
  }*/

  @Override
  public void setBeanName(String name) {
    this.beanName = name;
  }

  public void updateCronExpression(String newCronExpression) throws Exception {
    //Server, Component 등 Bean에 없으면 장애.
    Object iScheduledClass = applicationContext.getBean(this.beanName);
    IScheduled schedules = (IScheduled) iScheduledClass;

    if (schedules != null) {
      Runnable task = () -> {
        try {
          // 스케줄링 작업 수행
          applicationContext.getBean(this.getClass()).scheduledTask();
        } catch (Exception e) {
          // 예외 처리
          e.printStackTrace();
        }
      };

      unscheduleTask();
      CronTask cronTask = new CronTask(task, newCronExpression);
      scheduledFuture = taskRegistrar.getScheduler().schedule(cronTask.getRunnable(), cronTask.getTrigger());
    }
  }

  public void unscheduleTask() {
    if (scheduledFuture != null) {
      scheduledFuture.cancel(true);
      scheduledFuture = null;
    }
  }

  /*public void unscheduleTask() {
    //현재 버전에서 사용 불가능.
    if (cronTask != null) {
      for(int i = 0; i < taskRegistrar.getCronTaskList().size(); i++) {
        if(taskRegistrar.getCronTaskList().get(i).getRunnable().getClass().getSimpleName().toUpperCase()
                .contains(scheduledComponent.class.getSimpleName().toUpperCase())) {
          taskRegistrar.getCronTaskList().remove(i);
          cronTask = null;
          break;
        }
      }
    }
  }*/
}

 

인터페이스 Ischeduled

package ...

import org.springframework.scheduling.annotation.Scheduled;

public interface Ischeduled {
  @Scheduled
  void scheduledTask();
}

중간 반환.

package ...

import ...logMonitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class IiManager {
  private @Autowired LogMonitor logMonitor;

  public LogMonitor getlogMonitor() {
    return this.logMonitor;
  }
}

 

실사용 코드 작성

package ...

import scheduledComponent;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@EnableScheduling
public class LogMonitor extends ScheduledComponent {
  @Override
  public void scheduledTask() {
    /*System.out.println(new Date());
    System.out.println("asdfasdfas");*/

    try {
    } catch (Exception ex) {
    }
  }

  public void updateCronExpression(String newCronExpression) throws Exception {
    super.updateCronExpression(newCronExpression);
  }
}

 

변경 Call

if(config.getCodeValue().length() > 10) {
  manager.getLogMonitor().updateCronExpression(config.getCodeValue());
}

'Java' 카테고리의 다른 글

자바 스프링부트 버전업  (1) 2023.12.28
파이어베이스 다중 푸시  (0) 2023.10.16
Java region  (0) 2023.02.16
자바 열거형 Find Value  (1) 2022.09.23
자바 Jpa Entity -> Sql Default Value  (0) 2022.09.21