A job instance already exists and is complete for parameters

Sunday, January 2, 2011

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.

Solution for the above exception is:

The meaning of the above exception is one instancce(instance name) is already exists in db
To avoid the above exception we have to follow the following process

The following class is used to set job parameters dynamically


package raj.spring.batch;

import java.util.Calendar;
import java.util.Date;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersIncrementer;

 * @author nagarajuv

public class DynamicJobParameters implements JobParametersIncrementer {
 Date date = null;
 public JobParameters getNext(JobParameters parameters) {
  date = new Date();
  parameters = new JobParametersBuilder().addLong("currentTime", new Long(System.currentTimeMillis())).toJobParameters();
  return parameters;

define the dynamicJobParameters bean .xml file

<bean id="fileWritingJob" class="org.springframework.batch.core.job.SimpleJob" incrementer="dynamicJobParameters">

<bean id="dynamicJobParameters" class="com.ecomputercoach.DynamicJobParameters" />

Other wise we can follow other way alos

In our web application, In particular class we can set jobParameters to the job in the following way
Job job = null;
        JobParametersBuilder builder = null;
        JobParameters jobParameters = null;
        JobLauncher launcher = null;

        ApplicationContext context = AppContext.getApplicationContext();

        job = (Job) context.getBean("myjob");
        builder = new JobParametersBuilder();
        builder.addLong("currentTime", new Long(System.currentTimeMillis()));

        jobParameters = builder.toJobParameters();
        launcher = (JobLauncher) context.getBean("jobLauncher");
  launcher.run(job, jobParameters);

Tags:Spring batch job, dyamic parameters