Spring Batch Scheduler Example using Spring Boot

Spring Batch is one of the Spring modules and open-source frameworks used to build a lightweight and robust application. Spring Batch is mainly used for batch processing. Batch processing allows the execution of jobs automatically(i.e without human interaction). Let’s see how Spring Batch is useful.

  1. How to upload CSV file to Oracle/MySql database using Spring Batch.
  2. How to read data from the database and write it to CSV files.

Consider we have to read a large number of records from a database or some excel file or from the queue. One possible solution, we will have some rest endpoints that will read all data, modify the data and save data back to the database.

Another possible solution we want to happen these all processes automatically. It should read the data, modify them and save the data back into the database. Here Spring Batch can perform these tasks for us.

Note – On the basis of input resources, Spring Batch applications can be categorized as below.

  • Database driven applications – Intract with database(e.g MySql, Postgresql) for read & write operation.
  • File driven applications – Intract with File.
  • Message driven – Intract with Messaging Queue. See AWS queue example, Kafka messaging and Active MQ example.

Benefits of Spring Batch

  • Spring Batch can be used to process a large amount of data for example logging/tracing, transaction management, job processing, and resource management.
  • It allows us to perform a particular task at a scheduled time.

Create SpringMain.java and BatchTaskScheduler .java.

Create SpringMain.java

package com.springbatchexample.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages = "com.springbatchexample.*")
public class SpringMain {
    public static void main(final String[] args) {
        SpringApplication.run(SpringMain.class, args);
    }
}




TaskScheduler.java

package com.springbatchexample.scheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class BatchTaskScheduler {
    @Scheduled(fixedRate = 2000)
    public void performTask() {
        System.out.println("This is simple example using spring batch");
    }
}




Run the main class SpringMain.java. Tomcat will deploy and performTask() method will execute automatically at every 2 seconds.

Sample output:-

Spring Batch scheduler example

Let’s modify BatchTaskScheduler.java logic. The rest of the things should be the same.


@Component
public class BatchTaskScheduler {
    @Scheduled(fixedRate = 4000)
    public void exampleOfFixedrate() {
        Date date = new Date();
        String stringDateFormat = "hh:mm:ss a";
        DateFormat dateFormat = new SimpleDateFormat(stringDateFormat);
        //get current time
        String formattedDateAsString = dateFormat.format(date);
        System.out.println("This method will execute after every 4 sec " + formattedDateAsString);
    }
}




Output is –

This method will execute after every 4 sec 12:03:39 PM
This method will execute after every 4 sec 12:03:43 PM

That’s all about Spring batch task scheduling example using spring boot

Annotations used for Spring Batch scheduler.

@EnabledScheduling

  • This annotation enables Spring batch task scheduling feature.
  • This is available in org.springframework.scheduling.annotation package. See here documentation.
  • Mainly used with configuration class or Spring boot main class.

@Scheduled

  • This annotation is used to make any method scheduled.
  • Available in org.springframework.scheduling.annotation package. See here documentation.
  • We need to define attributes fixedDelay or fixedRate.
  • Attributes of @Scheduled annotation
    •  cron – An expression, triggers on the second, minute, hour, day of month, month and day of week.
    • fixedRate – if we give value 2000 for this, the method will get invoked after each 2 sec.
    • fixedRateString – behave similarly as the fixedRate only difference we can pass the value as String.
    • fixedDelay – if we give value 2000 for this, the method will get invoked after each 2 sec + time to execute that method. Suppose we have given the value for fixedDelay is 2000 i.e 2 sec and time taking to execute some method(with we are using fixedDelay) is 2 sec then total time will be 4 sec.
    • fixedDelayString –  behave similarly as the fixedRate only difference we can pass the value as String.
    • initialDelay – Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.
    • initialDelayString – Similar to initialDelay except we can pass the parameter as String.
    • zone – A time zone for which the cron expression will be resolved.

Download source code from GitHub.

That’s all about Spring Batch Scheduler Example using Spring Boot.