Java & Spring & SpringBoot

Spring Batch Job 실행 중 비정상적인 Job 상태 변경하는 법

Grand_J 2022. 7. 6. 13:46
반응형

Spring Batch Job 실행 중 비정상적인 Job 상태 변경하는 법

ContextRefreshedEventListener.java

import java.util.Date;
import java.util.Set;

import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


/**
 * Spring Batch Refresh 리스너
 * Spring Batch Job 실행 중 비정상적인 Job 에 대해서 status = stopped 로 변경
 *
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class ContextRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent>{

	private final JobExplorer jobExplorer;
	private final JobRepository jobRepository;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		log.info("Spring Batch Stop Running Job");
		
		for(String jobName : jobExplorer.getJobNames()) {
			
			Set<JobExecution> runningJobexExecutions = jobExplorer.findRunningJobExecutions(jobName);
			
			for(JobExecution jobExecution : runningJobexExecutions) {
				
				jobExecution.setStatus(BatchStatus.STOPPED);
				jobExecution.setEndTime(new Date());
				
				for (StepExecution stepExecution : jobExecution.getStepExecutions()) {					
					if(stepExecution.getStatus().isRunning()) {						
						stepExecution.setStatus(BatchStatus.STOPPED);
						stepExecution.setEndTime(new Date());
						jobRepository.update(stepExecution);						
					}					
				}
				
				jobRepository.update(jobExecution);
				log.info("Updated job execution status: ", jobExecution.getJobId());
				
			}
		}
		
		log.info("Spring Batch Stopped Running Job");
	}
	

}

개발 중 Job 실행 중 톰캣 restart를 하게 되면 Job이 수행 중이여서 동일 Job 생성 시 에러됨에 따라 정지하는 리스너 생성하면 됨

 

 

끗123#%@#$%!@#$

반응형