Spring Batch Tasklet example

In Spring batch, the Tasklet is an interface, which will be called to perform a single task only, like clean or set up resources before or after any step execution. In this example, we will show you how to use Tasklet to clean up the resource (folders) after a batch job is completed.

P.S The FileDeletingTasklet example below is taken from the Spring Batch samples project.

1. Tasklet Example

A Java class to implement Tasklet interface, and delete all the files in the given directory.

FileDeletingTasklet.java

package com.mkyong.tasklet;

import java.io.File;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

public class FileDeletingTasklet implements Tasklet, InitializingBean {

  private Resource directory;

  @Override
  public void afterPropertiesSet() throws Exception {
	Assert.notNull(directory, "directory must be set");
  }

  @Override
  public RepeatStatus execute(StepContribution contribution, 
               ChunkContext chunkContext) throws Exception {

	File dir = directory.getFile();
	Assert.state(dir.isDirectory());

	File[] files = dir.listFiles();
	for (int i = 0; i < files.length; i++) {
	  boolean deleted = files[i].delete();
	  if (!deleted) {
		throw new UnexpectedJobExecutionException(
                       "Could not delete file " + files[i].getPath());
	  } else {
	        System.out.println(files[i].getPath() + " is deleted!");
	  }
	}
	return RepeatStatus.FINISHED;
  }

  public Resource getDirectory() {
	return directory;
  }

  public void setDirectory(Resource directory) {
	this.directory = directory;
  }

}

2. Batch Jobs

A batch job to perform following steps :

Step 1 - To read multiple files from csv/inputs/, and write it to somewhere.
Step 2 - After step 1 is completed, run fileDeletingTasklet to delete all the files from directory csv/inputs/.

spring-batch-job.xml

  <job id="readMultiFileJob" xmlns="http://www.springframework.org/schema/batch">
	<step id="step1" next="deleteDir">
	  <tasklet>
		<chunk reader="multiResourceReader" writer="flatFileItemWriter"
			commit-interval="1" />
	  </tasklet>
	</step>
	<step id="deleteDir">
		<tasklet ref="fileDeletingTasklet" />
	</step>
  </job>
	
  <bean id="fileDeletingTasklet" class="com.mkyong.tasklet.FileDeletingTasklet" >
	<property name="directory" value="file:csv/inputs/" />
  </bean>
	
  <bean id="multiResourceReader"
	class=" org.springframework.batch.item.file.MultiResourceItemReader">
	<property name="resources" value="file:csv/inputs/domain-*.csv" />
	<property name="delegate" ref="flatFileItemReader" />
  </bean>
	

Download Source Code

Download it - SpringBatch-Tasklet-Example.zip (13 KB)

References

  1. Spring Batch TaskletStep
  2. Tasklet JavaDoc
  3. Spring batch samples

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
zoheir
Guest
zoheir

Hello Mkyong,
is there any documentation on the way to write a batch “spring batch” that can read data from various sources like, csv, xml, txt files and REST API, according to source detection type, than write the data to one destination repository ?

Neha
Guest
Neha

Hello Mkyong – Please develop a code to read data from mongoDB and write to XML file? Looking to get response on this.

Francisco López
Guest
Francisco López

What libraries are you using? i have a library error

Error creating bean with name ‘step1’: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException

Savani
Guest
Savani

I am facing same error as mentioned in the link –
(http://stackoverflow.com/questions/29478082/java-lang-illegalstateexception-assertion-failed-this-state-invariant-must)
Could you please guide?
Error for your reference:-
java.lang.IllegalStateException: [Assertion failed] – this state invariant must be true

test yz
Guest
test yz

char [] charArr; // need to be initialize
int [] lens = new int[charArr.length];

public static longestPanlidrom(int rightMost, int currentMid, int length) {
if(currentMid + length > rightMost) {
rightMost++;
if(charArr[currentMid – length] = charArr[rightMost])
length++;
} else {
if(charArr[currentMid – length] == char[currentMid + length]
}

}

trackback
Transaction Management in Spring Batch Components

[…] tasklet is repeatable: Spring Batch calls the execute method of a tasklet as long as the method returns RepeatStatus.CONTINUABLE. As we mentioned, each execute invocation […]

Ivan Tinajero
Guest
Ivan Tinajero

Hi !!

I was looking for some tutorials about java frameworks, specially spring and I found this site. This site is excellent, and it help me a lot with my project.

Thanks a lot for share your knowledge.

Regards.