본문 바로가기
프로그래밍/Spring

[스프링부트] EnableScheduling , Scheduled로 주기적인 스케쥴링 설정

by Mr-후 2023. 6. 8.
반응형

오늘은 인수인계 받은 소스를 들여다보다, 특정 테이블에 지속적으로 쌓이는 가비지 데이터를 삭제하기 위해 만들었던 것 같은데 주석 처리가 되어 있었다. 아마 매일, 새벽에 스케쥴러가 돌긴 했겠지만, 데이터는 삭제되지 않고 있었을 것 같다. 

글을 쓰다보니, 문득, 이런게 여러 곳에 있으면 위험할 것 같다는 생각도 든다. 소스에서는 운영서버가 아닐 경우에만 삭제가 되도록 되어 있는데 왜 그랬을까? 

데이터는 운영에서 적재될 것이고 적재된 데이터는 수십기가까지 증가할 수 있는 상황이고, 실제 그런 상황이 이러나, 가비지 데이터를 삭제하는 쿼리를 짜서 돌리고 있는 실정인데 말이다. 

여튼 몇 개의 어노테이션을 검색한 결과, 비교적 간단하게 spring에서 스케쥴링을 할 수 있다는 것을 알게 되었다. 


@Component
@Order(1)
@EnableScheduling
public class DataDeleteScheduleRunner {

    @Autowired
    private DataDeleteService dataDeleteService;

    @Autowired
    ProcessEnv processEnv;

    @Async
    @Scheduled(cron = "* * 3 * * ?") //매일 새벽 03시에 시작
    public void deleteGarbegeContent() {
        if (processEnv.isProduction()) {
            dataDeleteService.deleteGarbegeContent();
        }
    }
}

ProcessEnv.class 

  @Value("${process.env}")
  private String processEnv;
  
  public Boolean isProduction() {
    return StringUtils.isNotEmpty(processEnv) && processEnv.equals("production");
  }

 

@Order는 리스트형태로 주입 받는 빈(Bean)의 우선 순위가 필요할 사용하며, 그 인자의 숫자 값이 작을수록 우선순위가 높아 앞쪽에 정렬되고, 값이 클수록 우선순위가 낮아 뒤쪽에 정렬된다. 

@Scheduled의 경우 정의된 소스는 다음과 같고 사용법 간단하다. 

public @interface Scheduled {

	/**
	 * A special cron expression value that indicates a disabled trigger: {@value}.
	 * <p>This is primarily meant for use with <code>${...}</code> placeholders,
	 * allowing for external disabling of corresponding scheduled methods.
	 * @since 5.1
	 * @see ScheduledTaskRegistrar#CRON_DISABLED
	 */
	String CRON_DISABLED = ScheduledTaskRegistrar.CRON_DISABLED;


	/**
	 * A cron-like expression, extending the usual UN*X definition to include triggers
	 * on the second, minute, hour, day of month, month, and day of week.
	 * <p>For example, {@code "0 * * * * MON-FRI"} means once per minute on weekdays
	 * (at the top of the minute - the 0th second).
	 * <p>The fields read from left to right are interpreted as follows.
	 * <ul>
	 * <li>second</li>
	 * <li>minute</li>
	 * <li>hour</li>
	 * <li>day of month</li>
	 * <li>month</li>
	 * <li>day of week</li>
	 * </ul>
	 * <p>The special value {@link #CRON_DISABLED "-"} indicates a disabled cron
	 * trigger, primarily meant for externally specified values resolved by a
	 * <code>${...}</code> placeholder.
	 * @return an expression that can be parsed to a cron schedule
	 * @see org.springframework.scheduling.support.CronSequenceGenerator
	 */
	String cron() default "";

	/**
	 * A time zone for which the cron expression will be resolved. By default, this
	 * attribute is the empty String (i.e. the server's local time zone will be used).
	 * @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
	 * or an empty String to indicate the server's default time zone
	 * @since 4.0
	 * @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
	 * @see java.util.TimeZone
	 */
	String zone() default "";

	/**
	 * Execute the annotated method with a fixed period in milliseconds between the
	 * end of the last invocation and the start of the next.
	 * @return the delay in milliseconds
	 */
	long fixedDelay() default -1;

	/**
	 * Execute the annotated method with a fixed period in milliseconds between the
	 * end of the last invocation and the start of the next.
	 * @return the delay in milliseconds as a String value, e.g. a placeholder
	 * or a {@link java.time.Duration#parse java.time.Duration} compliant value
	 * @since 3.2.2
	 */
	String fixedDelayString() default "";

	/**
	 * Execute the annotated method with a fixed period in milliseconds between
	 * invocations.
	 * @return the period in milliseconds
	 */
	long fixedRate() default -1;

	/**
	 * Execute the annotated method with a fixed period in milliseconds between
	 * invocations.
	 * @return the period in milliseconds as a String value, e.g. a placeholder
	 * or a {@link java.time.Duration#parse java.time.Duration} compliant value
	 * @since 3.2.2
	 */
	String fixedRateString() default "";

	/**
	 * Number of milliseconds to delay before the first execution of a
	 * {@link #fixedRate} or {@link #fixedDelay} task.
	 * @return the initial delay in milliseconds
	 * @since 3.2
	 */
	long initialDelay() default -1;

	/**
	 * Number of milliseconds to delay before the first execution of a
	 * {@link #fixedRate} or {@link #fixedDelay} task.
	 * @return the initial delay in milliseconds as a String value, e.g. a placeholder
	 * or a {@link java.time.Duration#parse java.time.Duration} compliant value
	 * @since 3.2.2
	 */
	String initialDelayString() default "";
반응형