spring batch : contextRefreshedEventListener

This commit is contained in:
haerong22
2021-05-11 14:55:14 +09:00
parent 30ec8e1c18
commit 9268189974
2 changed files with 49 additions and 2 deletions

View File

@@ -38,7 +38,7 @@ public class CreateArticleJobConfig {
@Bean
public Job createArticleJob() {
return jobBuilderFactory.get("createArticleJob")
.incrementer(new RunIdIncrementer())
// .incrementer(new RunIdIncrementer())
.start(createArticleStep())
.build();
}
@@ -49,7 +49,7 @@ public class CreateArticleJobConfig {
.<ArticleModel, Article>chunk(1000)
.reader(createArticleReader())
.processor(createArticleProcessor())
.writer(createArticleWriterJDBC())
.writer(createArticleWriterJPA())
.build();
}

View File

@@ -0,0 +1,47 @@
package com.example.springbatch.application.listener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 java.util.Date;
import java.util.Set;
@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("Stop running jobs.");
for (String jobName : jobExplorer.getJobNames()) {
Set<JobExecution> runningJobExecutions = jobExplorer.findRunningJobExecutions(jobName);
for (JobExecution jobExecution : runningJobExecutions) {
log.warn("!!!!!!!!!!: {}, {} ", jobExecution.getJobId(), jobExecution.getStatus());
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("Stopped running jobs.");
}
}