Manas Saxena
Manas Saxena

Reputation: 2365

Pass current timestamp as a job parameter in spring batch

I am using spring batch, but due to job instance already exist error I need to add current time in my job parameter. I am unable to figure out where to add job parameters. Here is my code:

<step id="myStep">
 <tasklet>
  <chunk reader="myReader" processor="myProcessor" writer="myWriter" commit-interval="6000" skip-limit="9000">
  //some more code.
 </chunk>
 </tasklet>
</step>

<bean id="myReader" class="org.springframework,batch.item.database.StoredProcedueItemReader" scope="step">
 //define property for datasource , procedurename , rowmapper, parameters
 <property name="preparedStatementSetter" ref="myPreparedStatmentSetter">
</bean>

<bean id="myPreparedStatmentSetter" class="com.mypackage.MyPreparedStatementSetter" scope="step">
 <property name="kId" value="#{jobParameters[kId]}">
</bean>

When I try to run the job for same kId multiple times I get The job already exist error, so I need to add current timestamp to my job parameter. Would adding current time stamp as a property in the bean myPreparedStatmentSetter be sufficient, or do I need to add jobparameter somewhere else too? From where exactly are jobparameters picked from in spring file?

In case I need to add timestamp to the bean here is a questions -My stored procedure takes only kID as paramter, I dont need to pass current time stamp to stored procedure, then why I need to add the same in myPreparedStatmentSetter.

Also how would I add current timestamp in an xml file without java code?

EDIT

Here is my jobLauncher bean

<bean Id= "jobLauncher "class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
 <property name="jobRepository" value="myJobRepo">
</bean>

Upvotes: 1

Views: 5730

Answers (2)

Michael Minella
Michael Minella

Reputation: 21483

Adding a "random" job parameter by hand, while it can work, isn't the most ideal way to get around the job instance already exists error. Instead, you should consider adding a JobParametersIncrementer to your job. Spring provides the RunIdIncrementer as an implementation of this out of the box. A job configured with it would look something like the following:

@Bean
public Job myJob() { 
    return jobBuilderFactory.get("myJob")
                            .incrementer(runIdIncrementer())
                            .start(step1())
                            .build();
}

@Bean
public JobParametersIncrementer runIdIncrementer() {
    return new RunIdIncrementer();
}

Upvotes: 4

Vivek
Vivek

Reputation: 5

I am guessing that you already adding KId to your job parameters. Add following to your joblaucher.run() method.

new JobParametersBuilder()
.addLong("time",System.currentTimeMillis())
.addLong("KId",<your KID>)
.toJobParameters();

Upvotes: 1

Related Questions