스케줄러와 batch를 함께 사용하는 방법을 설명합니다.
job은 simplejob, otherjob 같이 2개가 있고 schedule에서 매 1분마다 simplejob만 실행하는 코드 입니다.
jobLancher와 jobRegistry를 사용하면 jar파일에 params를 넣어 실행하는 것이 아니라 프로그램 실행 중에 동적으로 job 실행 순서 및 스케줄링 가능합니다.
Jobs
simplejob
@Slf4j
@RequiredArgsConstructor
@Configuration
public class SimpleJobConfiguration {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
public static final String SIMPLE_JOB_NM = "SIMPLE_JOB";
private static final String SIMPLE_STEP_NM = "SIMPLE_TASKLET_STEP";
@Bean(name = SIMPLE_JOB_NM)
public Job simpleJob() {
return jobBuilderFactory.get(SIMPLE_JOB_NM)
.start(simpleStep())
.build();
}
@Bean(name = SIMPLE_STEP_NM)
public Step simpleStep() {
return stepBuilderFactory.get(SIMPLE_STEP_NM)
.tasklet((contribution, chunkContext) -> {
log.info(">>>>> simple job started >>>>>");
return RepeatStatus.FINISHED;
})
.build();
}
}
otherjob
@Slf4j
@Configuration
@RequiredArgsConstructor
public class OtherJobConfiguration {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
public static final String OTHER_JOB_NM = "OTHER_JOB";
private static final String OTHER_STEP_NM = "OTHER_TASKLET_STEP";
@Bean(name = OTHER_JOB_NM)
public Job otherJob() {
return jobBuilderFactory.get(OTHER_JOB_NM)
.start(otherStep())
.build();
}
@Bean(name = OTHER_STEP_NM)
public Step otherStep() {
return stepBuilderFactory.get(OTHER_STEP_NM)
.tasklet((contribution, chunkContext) -> {
log.info(">>>>> other job started >>>>>");
return RepeatStatus.FINISHED;
})
.build();
}
}
scheduler
private Job ExampleJob; 를 사용하면 모든 job이 실행됨.
jobRegistry를 사용하면 원하는 여러 개의 job 중 특정 name의 job 만 실행 가능하다
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Autowired
private JobRegistry jobRegistry;
@Bean
public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(){
JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor();
postProcessor.setJobRegistry(jobRegistry);
return postProcessor;
}
@Configuration
@Slf4j
public class JobScheduler {
@Autowired
private JobLauncher jobLauncher;
// @Autowired
// private Job ExampleJob;
@Scheduled(cron = "1 * * * * *")
public void jobSchduled() throws JobParametersInvalidException, JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException {
Map<String, JobParameter> jobParametersMap = new HashMap<>();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
Date time = new Date();
String time1 = format1.format(time);
jobParametersMap.put("date",new JobParameter(time1));
JobParameters parameters = new JobParameters(jobParametersMap);
//JobExecution jobExecution = jobLauncher.run(ExampleJob, parameters);
JobExecution jobExecution = jobLauncher.run(jobRegistry.getJob(SIMPLE_JOB_NM), parameters);
while (jobExecution.isRunning()) {
log.info("...");
}
log.info("Job Execution: " + jobExecution.getStatus());
log.info("Job getJobConfigurationName: " + jobExecution.getJobConfigurationName());
log.info("Job getJobId: " + jobExecution.getJobId());
log.info("Job getExitStatus: " + jobExecution.getExitStatus());
log.info("Job getJobInstance: " + jobExecution.getJobInstance());
log.info("Job getStepExecutions: " + jobExecution.getStepExecutions());
log.info("Job getLastUpdated: " + jobExecution.getLastUpdated());
log.info("Job getFailureExceptions: " + jobExecution.getFailureExceptions());
}
}
Application.properties
#스프링 배치 실행 시에 모든 잡이 실행기능 비활성
spring.batch.job.enabled=false
spring.batch.initialize-schema=always
Application
"@EnableBatchProcessing" 를 꼭 기입
package com.finnq.batch;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableBatchProcessing
public class FinnqBatchApplication {
public static void main(String args[]){
SpringApplication.run(FinnqBatchApplication.class, args);
}
}
build.gradle
dependencies {
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-batch', version: '2.3.9.RELEASE'
implementation group: 'org.springframework.integration', name: 'spring-integration-http', version: '5.2.11.RELEASE'
implementation group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.5.6'
//JDBC
implementation('org.springframework.boot:spring-boot-starter-jdbc')
//mybatis
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0'
//jpa
implementation group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.4.11'
runtime('com.h2database:h2')
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
compileOnly('org.projectlombok:lombok')
annotationProcessor('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
testImplementation group: 'org.springframework.batch', name: 'spring-batch-test', version: '4.2.2.RELEASE'
}
[참조]
정말 a to z로 기능 별로 잘 설명되어있음
https://blog.naver.com/PostView.nhn?blogId=sthwin&logNo=222144091181&parentCategoryNo=&categoryNo=49&viewDate=&isShowPopularPosts=false&from=postView
https://docs.spring.io/spring-batch/docs/current/reference/html/job.html#configuringJobLauncher
이미 실행 중인 job 스케줄링
https://jhw1308.tistory.com/41
jar 파일에 parameter 넘겨서 job 구분 실행하는 법
https://jojoldu.tistory.com/328
반응형
사업자 정보 표시
라울앤알바 | 장수호 | 서울특별시 관악구 봉천로 13나길 58-10, 404호(봉천동) | 사업자 등록번호 : 363-72-00290 | TEL : 010-5790-0933 | Mail : shjang@raulnalba.com | 통신판매신고번호 : 2020-서울관악-0892호 | 사이버몰의 이용약관 바로가기