Skip to content

Commit 0ad3423

Browse files
mmchsusanmaibin
authored andcommitted
how to trigger and stop scheduled batch job (eugenp#4671)
1 parent ca1a1d7 commit 0ad3423

5 files changed

Lines changed: 275 additions & 0 deletions

File tree

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
package org.baeldung.batchscheduler;
2+
3+
import java.util.Date;
4+
import java.util.IdentityHashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
import java.util.concurrent.ScheduledFuture;
8+
import java.util.concurrent.atomic.AtomicBoolean;
9+
10+
import org.baeldung.batchscheduler.model.Book;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
import org.springframework.batch.core.Job;
14+
import org.springframework.batch.core.JobExecution;
15+
import org.springframework.batch.core.JobParametersBuilder;
16+
import org.springframework.batch.core.Step;
17+
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
18+
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
19+
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
20+
import org.springframework.batch.core.launch.JobLauncher;
21+
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
22+
import org.springframework.batch.core.repository.JobRepository;
23+
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
24+
import org.springframework.batch.item.ItemWriter;
25+
import org.springframework.batch.item.file.FlatFileItemReader;
26+
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
27+
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
28+
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
29+
import org.springframework.beans.factory.annotation.Autowired;
30+
import org.springframework.context.annotation.Bean;
31+
import org.springframework.context.annotation.Configuration;
32+
import org.springframework.core.io.ClassPathResource;
33+
import org.springframework.scheduling.TaskScheduler;
34+
import org.springframework.scheduling.annotation.EnableScheduling;
35+
import org.springframework.scheduling.annotation.Scheduled;
36+
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
37+
import org.springframework.scheduling.support.ScheduledMethodRunnable;
38+
39+
@Configuration
40+
@EnableBatchProcessing
41+
@EnableScheduling
42+
public class SpringBatchScheduler {
43+
44+
private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class);
45+
46+
private AtomicBoolean enabled = new AtomicBoolean(true);
47+
48+
private Date currentLaunchDate;
49+
50+
private final Map<Object, ScheduledFuture<?>> scheduledTasks = new IdentityHashMap<>();
51+
52+
@Autowired
53+
private JobBuilderFactory jobBuilderFactory;
54+
55+
@Autowired
56+
private StepBuilderFactory stepBuilderFactory;
57+
58+
@Scheduled(fixedRate = 2000)
59+
public void launchJob() throws Exception {
60+
Date date = new Date();
61+
logger.debug("scheduler starts at " + date);
62+
if (enabled.get()) {
63+
currentLaunchDate = date;
64+
JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", currentLaunchDate)
65+
.toJobParameters());
66+
logger.debug("Batch job ends with status as " + jobExecution.getStatus());
67+
}
68+
logger.debug("scheduler ends ");
69+
}
70+
71+
public Date getCurrentLaunchDate() {
72+
return currentLaunchDate;
73+
}
74+
75+
public void stop() {
76+
enabled.set(false);
77+
}
78+
79+
public void start() {
80+
enabled.set(true);
81+
}
82+
83+
@Bean
84+
public TaskScheduler poolScheduler() {
85+
return new CustomTaskScheduler();
86+
}
87+
88+
private class CustomTaskScheduler extends ThreadPoolTaskScheduler {
89+
90+
private static final long serialVersionUID = -7142624085505040603L;
91+
92+
@Override
93+
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
94+
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
95+
96+
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
97+
scheduledTasks.put(runnable.getTarget(), future);
98+
99+
return future;
100+
}
101+
102+
}
103+
104+
public void cancelFutureSchedulerTasks() {
105+
scheduledTasks.forEach((k, v) -> {
106+
if (k instanceof SpringBatchScheduler) {
107+
v.cancel(false);
108+
}
109+
});
110+
}
111+
112+
@Bean
113+
public Job job() {
114+
return jobBuilderFactory.get("job")
115+
.start(readBooks())
116+
.build();
117+
}
118+
119+
@Bean
120+
public JobLauncher jobLauncher() throws Exception {
121+
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
122+
jobLauncher.setJobRepository(jobRepository());
123+
jobLauncher.afterPropertiesSet();
124+
return jobLauncher;
125+
}
126+
127+
@Bean
128+
public JobRepository jobRepository() throws Exception {
129+
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
130+
factory.setTransactionManager(new ResourcelessTransactionManager());
131+
return (JobRepository) factory.getObject();
132+
}
133+
134+
@Bean
135+
protected Step readBooks() {
136+
return stepBuilderFactory.get("readBooks")
137+
.<Book, Book> chunk(2)
138+
.reader(reader())
139+
.writer(writer())
140+
.build();
141+
}
142+
143+
@Bean
144+
public FlatFileItemReader<Book> reader() {
145+
return new FlatFileItemReaderBuilder<Book>().name("bookItemReader")
146+
.resource(new ClassPathResource("books.csv"))
147+
.delimited()
148+
.names(new String[] { "id", "name" })
149+
.fieldSetMapper(new BeanWrapperFieldSetMapper<Book>() {
150+
{
151+
setTargetType(Book.class);
152+
}
153+
})
154+
.build();
155+
}
156+
157+
@Bean
158+
public ItemWriter<Book> writer() {
159+
return new ItemWriter<Book>() {
160+
161+
@Override
162+
public void write(List<? extends Book> items) throws Exception {
163+
logger.debug("writer..." + items.size());
164+
for (Book item : items) {
165+
logger.debug(item.toString());
166+
}
167+
168+
}
169+
};
170+
}
171+
172+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.batchscheduler.model;
2+
3+
public class Book {
4+
private int id;
5+
private String name;
6+
7+
public Book() {}
8+
9+
public Book(int id, String name) {
10+
super();
11+
this.id = id;
12+
this.name = name;
13+
}
14+
15+
public int getId() {
16+
return id;
17+
}
18+
19+
public void setId(int id) {
20+
this.id = id;
21+
}
22+
23+
public String getName() {
24+
return name;
25+
}
26+
27+
public void setName(String name) {
28+
this.name = name;
29+
}
30+
31+
public String toString() {
32+
return "Book [id=" + id + ", name=" + name + "]";
33+
}
34+
35+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
1,SHARP OBJECTS (MOVIE TIE-IN): A NOVEL
2+
2,ARTEMIS: A NOVEL
3+
3,HER PRETTY FACE
4+
4,ALL WE EVER WANTED

‎spring-batch/src/main/resources/logback.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212
additivity="false">
1313
<appender-ref ref="STDOUT" />
1414
</logger>
15+
16+
<logger name="org.baeldung.batchscheduler" level="debug" additivity="false">
17+
<appender-ref ref="STDOUT" />
18+
</logger>
1519

1620
<root level="error">
1721
<appender-ref ref="STDOUT" />
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package org.baeldung.batchscheduler;
2+
3+
import java.util.Date;
4+
5+
import org.junit.Assert;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.context.ApplicationContext;
10+
import org.springframework.scheduling.TaskScheduler;
11+
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
12+
import org.springframework.test.context.ContextConfiguration;
13+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
14+
15+
@RunWith(SpringJUnit4ClassRunner.class)
16+
@ContextConfiguration(classes = SpringBatchScheduler.class)
17+
public class SpringBatchSchedulerIntegrationTest {
18+
19+
private static final int TIMER = 3000;
20+
21+
@Autowired
22+
private ApplicationContext context;
23+
24+
@Test
25+
public void stopJobsWhenSchedulerDisabled() throws Exception {
26+
Thread.sleep(TIMER);
27+
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
28+
schedulerBean.stop();
29+
Thread.sleep(TIMER);
30+
Date lastLaunchDate = schedulerBean.getCurrentLaunchDate();
31+
Thread.sleep(TIMER);
32+
Assert.assertEquals(lastLaunchDate, schedulerBean.getCurrentLaunchDate());
33+
}
34+
35+
@Test
36+
public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception {
37+
Thread.sleep(TIMER);
38+
ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class);
39+
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
40+
bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler");
41+
Thread.sleep(TIMER);
42+
Date lastLaunchTime = schedulerBean.getCurrentLaunchDate();
43+
Thread.sleep(TIMER);
44+
Assert.assertEquals(lastLaunchTime, schedulerBean.getCurrentLaunchDate());
45+
46+
}
47+
48+
@Test
49+
public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception {
50+
Thread.sleep(TIMER);
51+
SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class);
52+
schedulerBean.cancelFutureSchedulerTasks();
53+
Thread.sleep(TIMER);
54+
Date lastLaunchTime = schedulerBean.getCurrentLaunchDate();
55+
Thread.sleep(TIMER);
56+
Assert.assertEquals(lastLaunchTime, schedulerBean.getCurrentLaunchDate());
57+
58+
}
59+
60+
}

0 commit comments

Comments
 (0)