使用Spring Batch 2.2.0.RELEASE,并使用Spring Scheduler启动作业。
CustomJobLauncher.java
package com.mkyong.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CustomJobLauncher {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
public void run() {
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
}
}
job-config.xml
<bean id="customJobLauncher" class="com.mkyong.batch.CustomJobLauncher" />
<task:scheduled-tasks>
<task:scheduled ref="customJobLauncher" method="run" fixed-delay="10000" />
</task:scheduled-tasks>
问题
批处理作业仅在第一次成功运行,第二次启动(10秒后)时,将提示以下错误消息。
org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException:
A job instance already exists and is complete for parameters={}.
If you want to run this job again, change the parameters.
at org.springframework.batch.core.repository.support.SimpleJobRepository.createJobExecution(SimpleJobRepository.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
解
请参考上面的错误消息“ 如果要再次运行此作业,请更改参数。 公式是JobInstance = JobParameters + Job
。 如果您没有JobParameters
任何参数,只需将当前时间作为参数来创建一个新的JobInstance
。 例如,
CustomJobLauncher.java
//...
@Component
public class CustomJobLauncher {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
public void run() {
try {
JobParameters jobParameters =
new JobParametersBuilder()
.addLong("time",System.currentTimeMillis()).toJobParameters();
JobExecution execution = jobLauncher.run(job, jobParameters);
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
}
}
参考文献
标签: Spring批