Spring boot batch processing is the automated processing of large volumes of data without the participation of a person. Tasklet is a spring boot batch interface that is used to do a single action in a step. A tasklet is a spring boot task that performs a single operation when the spring boot batch is run. If the spring boot batch is executed, the Tasklet interface’s execute method is invoked.
The spring boot batch will be run at regular intervals. When the batch is executed, a batch job is created that will invoke the spring boot batch step. The Tasklet class is configured in the batch steps. One or more Tasklet-implemented java classes can be defined for a step. The step will run all of the Tasklet class objects in sequence. The Tasklet class is used to do a single task at a time.
In this example, the Tasklet interface is used to implement a spring boot batch task. The spring boot scheduler will execute the spring boot batch job, which interns refer to as the batch step. The step includes the Tasklet-implemented Task. When the step is done, the task will be completed.
Tasklet Interface
Tasklet is a batch interface for spring boot. It is used to define a single action or job. A class should be created by implementing Tasklet interface. The Tasklet interface has an execute method, which is invoked when the batch is run. In the following example, a class is created by implementing the Tasklet interface. The class includes an implementation of the execute function.
MyTask.java
package com.yawintutor;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class MyTask implements Tasklet {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
System.out.println("MyTask:execute: executing tasklet - "+format.format(Calendar.getInstance().getTime()));
return null;
}
}
Batch Configuration
There are two methods in the spring boot batch configuration. The first method will create a Batch job, whereas the second will create a Batch step. The Batch step will be created using the Tasklet interface-implemented task class. The batch step will be executed by the batch job.
BatchConfig.java
package com.yawintutor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Bean
public Job createJob() {
return jobBuilderFactory.get("MyJob")
.incrementer(new RunIdIncrementer())
.start(createStep()).build();
}
@Bean
public Step createStep() {
return stepBuilderFactory.get("MyStep").tasklet(new MyTask()).build();
}
}
Spring Boot Batch Scheduler
Spring boot batch schedulers are used to setup the spring boot batch to run automatically based on the scheduler configuration. If it is configured using a scheduler, no human interaction is necessary. The scheduler can be set as a fixed delay, fixed rate, or cron task.
SchedulerConfig.java
package com.yawintutor;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class SchedulerConfig {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
@Scheduled(fixedRate = 5000)
public void scheduleByFixedRate() throws Exception {
System.out.println("Batch job starting");
JobParameters jobParameters = new JobParametersBuilder()
.addString("time", format.format(Calendar.getInstance().getTime())).toJobParameters();
jobLauncher.run(job, jobParameters);
System.out.println("Batch job executed successfully\n");
}
}
Spring Boot Main Class
The main class for the spring boot is shown here. The spring boot main class has no extra configuration.
SpringBootBatch1Application
package com.yawintutor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootBatch1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootBatch1Application.class, args);
}
}
Application.properties
Two configurations in the application.properties file are required for the spring boot batch. The first property is used to specify the database url. The h2 database is used in this example. In application.properties, the h2 database url is specified. The batch-related database table is created in the second configuration. The batch default tables are automatically created.
application.properties
spring.datasource.url=jdbc:h2:file:./DB
spring.batch.initialize-schema=ALWAYS
Pom.xml
The spring boot batch pom.xml file is shown as below. The pom.xml contains the spring boot batch related dependencies and database related dependencies.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yawintutor</groupId>
<artifactId>SpringBootBatch1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootBatch1</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
How to run
If the spring boot application is executed with the above configuration and code, the spring boot batch will be executed periodically. In the example, the scheduler is configured with 5 seconds. The logs will be created once in 5 seconds. The logs will show as below.
Batch job starting
[2m2021-07-21 09:46:29.960[0;39m [32m INFO[0;39m [35m58448[0;39m [2m---[0;39m [2m[ scheduling-1][0;39m [36mo.s.b.c.l.support.SimpleJobLauncher [0;39m [2m:[0;39m Job: [SimpleJob: [name=MyJob]] launched with the following parameters: [{time=2021-07-21 09:46:29.955}]
[2m2021-07-21 09:46:29.965[0;39m [32m INFO[0;39m [35m58448[0;39m [2m---[0;39m [2m[ scheduling-1][0;39m [36mo.s.batch.core.job.SimpleStepHandler [0;39m [2m:[0;39m Executing step: [MyStep]
MyTask:execute: executing tasklet - 2021-07-21 09:46:29.967
[2m2021-07-21 09:46:29.969[0;39m [32m INFO[0;39m [35m58448[0;39m [2m---[0;39m [2m[ scheduling-1][0;39m [36mo.s.batch.core.step.AbstractStep [0;39m [2m:[0;39m Step: [MyStep] executed in 4ms
[2m2021-07-21 09:46:29.972[0;39m [32m INFO[0;39m [35m58448[0;39m [2m---[0;39m [2m[ scheduling-1][0;39m [36mo.s.b.c.l.support.SimpleJobLauncher [0;39m [2m:[0;39m Job: [SimpleJob: [name=MyJob]] completed with the following parameters: [{time=2021-07-21 09:46:29.955}] and the following status: [COMPLETED] in 10ms
Batch job executed successfully