Batch processing is about repetitive actions – either as a simple optimization, or as part of a job. To strategize and generalize the repetition as well as to provide what amounts to an iterator framework, Spring Batch has the RepeatOperations interface. The RepeatOperations interface looks like this:
public interface RepeatOperations { RepeatStatus iterate(RepeatCallback callback) throws RepeatException; }
The callback is a simple interface that allows you to insert some business logic to be repeated:
public interface RepeatCallback { RepeatStatus doInIteration(RepeatContext context) throws Exception; }
The callback is executed repeatedly until the implementation decides that the iteration should end. The return value in these interfaces is an enumeration that can either be RepeatStatus.CONTINUABLE or RepeatStatus.FINISHED. A RepeatStatus conveys information to the caller of the repeat operations about whether there is any more work to do. Generally speaking, implementations of RepeatOperations should inspect the RepeatStatus and use it as part of the decision to end the iteration. Any callback that wishes to signal to the caller that there is no more work to do can return RepeatStatus.FINISHED.
The simplest general purpose implementation of RepeatOperations is RepeatTemplate. It could be used like this:
RepeatTemplate template = new RepeatTemplate(); template.setCompletionPolicy(new FixedChunkSizeCompletionPolicy(2)); template.iterate(new RepeatCallback() { public ExitStatus doInIteration(RepeatContext context) { // Do stuff in batch... return ExitStatus.CONTINUABLE; } });
In the example we return RepeatStatus.CONTINUABLE to show that there is more work to do. The callback can also return ExitStatus.FINISHED if it wants to signal to the caller that there is no more work to do. Some iterations can be terminated by considerations intrinsic to the work being done in the callback, others are effectively infinite loops as far as the callback is concerned and the completion decision is delegated to an external policy as in the case above.
RepeatContext-
The method parameter for the RepeatCallback is a RepeatContext. Many callbacks will simply ignore the context, but if necessary it can be used as an attribute bag to store transient data for the duration of the iteration. After the iterate method returns, the context will no longer exist.
A RepeatContext will have a parent context if there is a nested iteration in progress. The parent context is occasionally useful for storing data that need to be shared between calls to iterate. This is the case for instance if you want to count the number of occurrences of an event in the iteration and remember it across subsequent calls.
RepeatStatus-
RepeatStatus is an enumeration used by Spring Batch to indicate whether processing has finished. These are possible RepeatStatus values:
CONTINUABLE-There is more work to do.
FINISHED-No more repetitions should take place.