spring batch結合定時任務記錄每一次結果
阿新 • • 發佈:2019-01-22
1.當我們不知道程式怎麼跑的時候是十分可怕的,所有對於定時任務,我們需要把每一次的執行細節,傳入的引數,執行的結果等儲存到資料庫中。那麼怎樣儲存那。我這裡給出一個方案。springbatch。
2.專案基礎springboot,maven,druid。
(1)maven中引入jar:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency>
@Configuration @EnableBatchProcessing @ComponentScan(basePackageClasses = DefaultBatchConfigurer.class) public class ShopJobConfig { @Autowired private JobBuilderFactory jobs; @Autowired private StepBuilderFactory steps; @Autowired private ShopTask shopTask; @Bean public Job job(Step step1) { return jobs.get("shopJob").incrementer(new RunIdIncrementer()).start(step1).build(); } @Bean public Step Step1() { MethodInvokingTaskletAdapter adapter = new MethodInvokingTaskletAdapter(); adapter.setTargetObject(shopTask); adapter.setTargetMethod("doTask"); return steps.get("shopJobStep1").tasklet(adapter).build(); } }
(2)配置一個job,來執行我們的任務
@Component
public class ShopTaskImpl implements ShopTask{
@Override
public void doTask() {
System.out.println("task execute");
}
}
(3)配置一個定時任務來執行:
@Component public class ScheduledTasks { @Autowired private JobLauncher jobLauncher; @Autowired private Job job; @Scheduled(cron="0/5 * * * * * ") public void showCurrentTime() throws Exception{ System.out.println(1); Map<String, JobParameter> param = new HashMap<String, JobParameter>(); param.put("startTime", new JobParameter(new Date())); jobLauncher.run(job, new JobParameters(param)); System.out.println(1); } }
(4)檢視資料庫:
spring.batch.job.enabled=false