Java Reference
In-Depth Information
public class DailyJobTimestamper implements JobParametersIncrementer {
/**
* Increment the current.date parameter.
*/
public JobParameters getNext( JobParameters parameters ) {
Date today = new Date();
if ( parameters != null && !parameters.isEmpty() ) {
Date oldDate = parameters.getDate( "current.date", new Date() );
today = DateUtils.addDays(oldDate, 1);
}
return new JobParametersBuilder().addDate( "current.date", today )
.toJobParameters();
}
}
It's pretty obvious that job parameters are an important part of the framework. They allow you to
specify values at runtime for your job. They also are used to uniquely identify a run of your job. You use
them more throughout the topic for things like configuring the dates for which to run the job and
reprocessing error files. For now, let's look at another powerful feature at the job level: job listeners.
Working with Job Listeners
When you use a web application, feedback is essential to the user experience. A user clicks a link, and the
page refreshes within a few seconds. However, as you've seen, batch processes don't provide much in
the way of feedback. You launch a process, and it runs. That's it. Yes, you can query the job repository to
see the current state of your job, and there is the Spring Batch Admin web application, but many times
you may want something to happen at a given point in your job. Say you want to send an email if a job
fails. Maybe you want to log the beginning and ending of each job to a special file. Any processing you
want to occur at the beginning (once the JobExecution is created and persisted but before the first step is
executed) or end of a job is done with a job listener.
There are two ways to create a job listener. The first is by implementing the
org.springframework.batch.core.JobExecutionListener interface. This interface has two methods of
consequence: beforeJob and afterJob . Each takes JobExecution as a parameter, and they're executed—
you guessed it, before the job executes and after the job executes, respectively. One important thing to
note about the afterJob method is that it's called regardless of the status the job finishes in. Because of
this, you may need to evaluate the status in which the job ended to determine what to do. Listing 4-17
has an example of a simple listener that prints out some information about the job being run before and
after as well as the status of the job when it completed.
Listing 4-17. JobLoggerListener.java
package com.apress.springbatch.chapter4;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
public class JobLoggerListener implements JobExecutionListener {
 
Search WWH ::




Custom Search