투케이2K

21. (spring/스프링) EnableScheduling , Scheduled 사용해 주기적 스케줄링 반복 작업 수행 실시 본문

Spring

21. (spring/스프링) EnableScheduling , Scheduled 사용해 주기적 스케줄링 반복 작업 수행 실시

투케이2K 2021. 8. 23. 09:27
반응형

[개발 환경 설정]

개발 툴 : inteli j

개발 언어 : spring


[로직 설명]

- 서버 애플리케이션 실행 시 등록된 스케줄링 자동 실행 설정

- 스케줄링 작업 코드 작성

- 동시 스케줄링을 실행하기 위한 스레드 풀 config 설정


[폴더 및 파일 설정]


[소스코드 : SolutionPackageApplication]

package com.project.solutionpackage;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication

// [애플리케이션 서버 실행 시 자동 스케줄링 실행 설정]
@EnableScheduling
public class SolutionPackageApplication {

    public static void main(String[] args) {
        SpringApplication.run(SolutionPackageApplication.class, args);
    }

}

[소스코드 : service >> ScheduleService]

package com.project.solutionpackage.service;

import com.project.solutionpackage.model.Font;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

// [컴포넌트 어노테이션 : 개발자가 직접 작성한 클래스를 빈으로 등록 실시]
@Component
public class ScheduleService {

    // [현재 날짜 및 시간을 확인하는 메소드]
    public static String getNowDateTime24() {
        //long 타입으로 System.currentTimeMillis() 데이터를 받아야합니다
        long time = System.currentTimeMillis();
        SimpleDateFormat dayTime = new SimpleDateFormat("yyyy.MM.dd kk:mm:ss E요일");
        String str = dayTime.format(new Date(time));
        return str; //return은 메소드 호출 후 데이터를 반환해줍니다
    }



    // [2초 후 3초마다 반복 실행 스케줄링]
    @Scheduled(fixedDelay = 3000,  initialDelay = 2000)
    public void threeRepeatJob(){
        System.out.println("\n");
        System.out.println("=======================================");
        System.out.println("[ScheduleService] : [threeRepeatJob] : [start]");
        System.out.println("[JopTime] : " + getNowDateTime24());
        System.out.println("=======================================");
        System.out.println("\n");
    }




    // [1초 후 5초마다 반복 실행 스케줄링]
    @Scheduled(fixedDelay = 5000,  initialDelay = 1000)
    public void fiveRepeatJob(){
        System.out.println("\n");
        System.out.println("=======================================");
        System.out.println("[ScheduleService] : [fiveRepeatJob] : [start]");
        System.out.println("[JopTime] : " + getNowDateTime24());
        System.out.println("=======================================");
        System.out.println("\n");
    }



    // [매일 오전 8시 58분에 실행되는 스케줄링]
    // [* 초(0-59)     * 분(0-59)   * 시간(0-23)   * 일(1-31)  * 월(1-12)  * 요일(0-7)]
    @Scheduled(cron = "0 58 8 * * *")
    public void everyDay_M_8_58_RepeatJob(){
        System.out.println("\n");
        System.out.println("=======================================");
        System.out.println("[ScheduleService] : [everyDay_M_8_58_RepeatJob] : [start]");
        System.out.println("[JopTime] : " + getNowDateTime24());
        System.out.println("=======================================");
        System.out.println("\n");
    }

}

[소스코드 : config >> SchedulerConfig]

package com.project.solutionpackage.config;

import com.project.solutionpackage.model.Font;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

// [Configuration 어노테이션 : 자바 클래스 파일을 설정 파일로 사용]
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
    private final int POOL_SIZE = 10;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        // [스레드 풀을 사용해서 모든 예약된 스케줄 작업이 실행되도록 설정]
        // [스프링에서는 스케줄링 작업은 한개의 스레드 풀에서 실행되기때문에 >> 다중 동시 실행을 위해서 스레드 풀 설정 실시]
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix("scheduled-task-pool-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
        System.out.println("\n");
        System.out.println("=======================================");
        System.out.println("current thread : " + Thread.currentThread().getName());
        System.out.println("=======================================");
        System.out.println("\n");
    }
}

[결과 출력]

 


 

반응형
Comments