EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Batch Scheduler
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Batch Scheduler

Spring Batch Scheduler

Definition of Spring Batch Scheduler

It is the framework available in spring batch which was used to run scheduled jobs at specific time. One of the open-source batch processing frameworks is Spring Batch. We may need to run spring batch jobs frequently or on a set schedule while working in any application. This is accomplished by passing spring task scheduler a cron expression. We can enable the scheduling by using @EnableScheduling annotation.

Spring Batch Scheduler overview

  • Spring batch has been brought out to initiate batch jobs starting with version 3. x. In below example, we putting up a simple Job using a tasklet which was runs a select query on PostgreSQL database table.
  • While using this, the tasklet will run on a regular basis. Below is the term which was related as follows.

1) Jobs
2) TransactionManager
3) JobRepository
4) JobLauncher

  • Jobs are made up of steps, each of which may include a reader, a writer, and a processor.
  • TransactionManager is a class that is used to start and commit transactions as they are being processed.
  • Persistence is possible with Spring Batch’s JobRepository. For JobLauncher, Job, and Step instantiations, it provides CRUD operations.
  • JobLauncher provides a straightforward interface for starting a job using a collection of JobParameters.
  • Batch job scheduling can be configured using the annotation name as @EnableScheduling and a method annotated with @Scheduled followed by cron job time information, ensuring that the execution logic runs at the specified time.

Batch job scheduling requires two steps to configure:-

1) The annotation @EnableScheduling enables scheduling.

2) Create a @Scheduled function and use a cron job to supply the recurrence details. Within this method, put the job execution logic.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)
  • To schedule a job, we need to add spring batch core dependency in pom.xml file.

Creating spring batch scheduler

  • We have used the project template name as SpringBatchScheduler.
  • Below example shows how to create scheduler in spring batch are as follows.

Code:

public class Scheduler {
@Autowired
private JobLauncher lcr;
@Autowired
private Job j;
private JobExecution ex;
public void run() throws org.springframework.batch.core.repository.JobRestartException {
try {
org.springframework.batch.core.JobExecution ex1 = lcr.run(j, new JobParameters());
System.out.println("Status of execution: "+ ex.getBatchStatus());
} catch (JobExecutionAlreadyRunningException e) {
e.printStackTrace();
} catch (JobRestartException e) {
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
e.printStackTrace();
} catch (JobParametersInvalidException e) {
e.printStackTrace();
}
}
public JobLauncher getLcr() {
return lcr;
}
public void setLcr (JobLauncher lcr) {
this.lcr = lcr;
}
public Job getJ() {
return j;
}
public void setJ(Job j) {
this.j = j;
}
public JobExecution getEx() {
return ex;
}

Spring Batch Scheduler 2

Scheduled Spring Batch Job

  • We’ll put up a simple Job by using a tasklet that runs a select query on a PostgreSQL database table and prints the results.
  • Using the Spring Batch tasklet Scheduler, the Tasklet will be running on a regular basis.
  • The spring batch scheduler will execute as per the time which was we have scheduled in our application.
  • We can do the scheduling of spring batch by using spring task scheduler. Spring batch task scheduler is very important to implement scheduler in our application.

Project Set-up

1) Create project template of spring batch tasklet by using spring initializer

  • In below step we have providing project group name as com.example, artifact name as SpringBatchScheduler, project name as SpringBatchScheduler, and selected java version as 8. Also, we have defined spring boot version is 2.6.0, defined project as maven.
  • In below project we have selected spring web, spring batch, and PostgreSQL driver dependency to implement spring batch project.

Group – com. example Artifact name – SpringBatchScheduler
Name – SpringBatchScheduler Spring boot – 2.6.0
Project – Maven Java – 8
Package name - com.example.SpringBatchScheduler
Project Description - Project for SpringBatchScheduler
Dependencies – spring web, PostgreSQL driver, spring batch.

Spring Batch Scheduler 4

2) After generating project extract files and open this project by using spring tool suite –

After generating the project by using spring initializer in this step we are extracting the jar file and opening project by using spring tool suite.

Spring Batch Scheduler 5

3) After opening project using spring tool suite check the project and its files –

In this step, we are checking all the project template files. We also need to check maven dependencies and system libraries.

Spring Batch Scheduler 6

4) Add dependency packages –

In this step, we are adding the spring batch dependency in project.

Code:

<dependency> -- Start of dependency tag.
<groupId>org.springframework</groupId> -- Start and end of groupId tag.
<artifactId>spring-core</artifactId> -- Start and end of artifactId tag.
</dependency> -- End of dependency tag.
<dependency> -- Start of dependency tag.
<groupId>org.postgresql</groupId> -- Start and end of groupId tag.
<artifactId>postgresql</artifactId> -- Start and end of artifactId tag.
</dependency> -- End of dependency tag.

7

Spring batch scheduler example

We are using SpringBatchScheduler template to define the example.

1) Set up pojo –

Code:

public class pScheduler {
String stud_name;
public String getstudName() {
return stud_name;
}
public void setFirstName (String name) {
this.stud_name = name;
}
@Override
public String toString(){
return "Stud, "+stud_name+"";
}
}

8

2) Create the tasklet –

Code:

public class SBTasklet implements Tasklet{
private DataSource ds;
private String sql_query="select stud_name from stud";
public RepeatStatus execute (StepContribution contribution,
ChunkContext chunkContext) throws Exception {
ArrayList stud_list = new ArrayList();
JdbcTemplate myTemplate = new JdbcTemplate(getDataSource());
stud_list = SBTasklet.sql_query (sql_query, new studMapper ());
return RepeatStatus.FINISHED;
}
private static ArrayList sql_query(String sql_query2, studMapper studMapper) {
return null;
}
public DataSource getDataSource() {
return ds;
}
public void setDataSource (DataSource DBS) {
this.ds = DBS;
}
}

9

3) Create scheduler, configure the job, and run the scheduler –

We have already created scheduler so we have no need to create and configure it again now we have running the scheduler.

Code:

public class MainSchedule {
public static void main(String[] args) {
String[] str = {"classpath:META-INF/spring/job-config.xml","classpath:META-INF/spring/context-config.xml"};
ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext (str);
}
}

11

4) Run the scheduler

12

Conclusion

In spring batch scheduling we can enable scheduling by using @EnableScheduling annotation. While using the Spring Batch Scheduler, the tasklet will run on a regular basis. Spring batch scheduler is the framework available in spring batch which was used to run scheduled jobs at specific time.

Recommended Articles

This is a guide to Spring Batch Scheduler. Here we discuss What is azure log analytics, How to create Azure Log Analytics, and tools. You may also have a look at the following articles to learn more –

  1. Spring Boot Advantages
  2. Spring Boot Initializr
  3. Spring Boot Maven
  4. Spring Boot Cache
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more