|
| 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 | +} |
0 commit comments