HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Batch / Spring batch job scheduling with Spring TaskScheduler

Spring batch job scheduling with Spring TaskScheduler

In enterprise applications, you will need to execute spring batch jobs periodically on fixed schedule using some cron expression passed to Spring TaskScheduler. In this example, we will execute our example spring batch job using spring’s inbuilt scheduling capability.

Configure batch job scheduler

To configure, batch job scheduling is done in two steps:

  1. Enable scheduling with @EnableScheduling annotation.
  2. Create method annotated with @Scheduled and provide recurrence details using cron job. Add the job execution logic inside this method.
package com.howtodoinjava.demo;

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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
public class App
{
	@Autowired
	JobLauncher jobLauncher;
	
	@Autowired
	Job job;
	
	public static void main(String[] args) 
	{
		SpringApplication.run(App.class, args);
	}
	
	@Scheduled(cron = "0 */1 * * * ?")
    public void perform() throws Exception 
	{
		JobParameters params = new JobParametersBuilder()
				.addString("JobID", String.valueOf(System.currentTimeMillis()))
				.toJobParameters();
		jobLauncher.run(job, params);
	}
}

Above batch job will run every one minute after application is started.

To refer the job and task sourcecode, please read Spring batch Java config example.

Demo

Now if you run the application and verify logs, you will see that job is running every minute.

2018-07-04 15:57:00.073  INFO 7320 --- [pool-1-thread-1] o.s.b.c.l.support.SimpleJobLauncher      
: Job: [SimpleJob: [name=demoJob]] launched with the following parameters: [{JobID=1530700020003}]

2018-07-04 15:57:00.097  INFO 7320 --- [pool-1-thread-1] o.s.batch.core.job.SimpleStepHandler     
: Executing step: [stepOne]

MyTaskOne start..
MyTaskOne done..

2018-07-04 15:57:00.118  INFO 7320 --- [pool-1-thread-1] o.s.batch.core.job.SimpleStepHandler     
: Executing step: [stepTwo]

MyTaskTwo start..
MyTaskTwo done..

2018-07-04 15:57:00.125  INFO 7320 --- [pool-1-thread-1] o.s.b.c.l.support.SimpleJobLauncher      
: Job: [SimpleJob: [name=demoJob]] completed with the following parameters: [{JobID=1530700020003}] 
and the following status: [COMPLETED]

2018-07-04 15:58:00.007  INFO 7320 --- [pool-1-thread-1] o.s.b.c.l.support.SimpleJobLauncher      
: Job: [SimpleJob: [name=demoJob]] launched with the following parameters: [{JobID=1530700080002}]

2018-07-04 15:58:00.011  INFO 7320 --- [pool-1-thread-1] o.s.batch.core.job.SimpleStepHandler     
: Executing step: [stepOne]

MyTaskOne start..
MyTaskOne done..

2018-07-04 15:58:00.021  INFO 7320 --- [pool-1-thread-1] o.s.batch.core.job.SimpleStepHandler     
: Executing step: [stepTwo]

MyTaskTwo start..
MyTaskTwo done..

2018-07-04 15:58:00.029  INFO 7320 --- [pool-1-thread-1] o.s.b.c.l.support.SimpleJobLauncher      
: Job: [SimpleJob: [name=demoJob]] completed with the following parameters: [{JobID=1530700080002}] 
and the following status: [COMPLETED]

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. RK

    June 25, 2020

    Hi Lockesh,

    I am having a standalone server where these spring batch jobs are scheduled via CRON jobs. Want to know how to achieve HA with another backup server. Incase of any Job failed in middle or server down – other server should be able to pick the job execution (from scratch is also fine). Any suggestions? Thanks in advance.

  2. Sachin

    May 22, 2020

    HI , I want to Schedule two different Job, what i need to do.
    lets say i have JobA i want to run at 10 PM and JobB i want to run 11 PM , Can you give me example how to do that using annotations

  3. Abhijet Khambe

    September 12, 2019

    Hi Lokesh,
    I have a requirement where I need to read a particular column value from oracle database and pass that to a different database. Every day we are expecting to read millions of records from database. Please let me know if a simple Listener job would suffice or we need to something extra?

    • Lokesh Gupta

      September 12, 2019

      Never faced this problem. I am not the best person to suggest this.

  4. Saravanan

    August 2, 2019

    I want to set the value of cron dynamically using following approach. Any help would be appreciated.

    https://stackoverflow.com/questions/14630539/scheduling-a-job-with-spring-programmatically-with-fixedrate-set-dynamically

  5. vinod kumar

    June 23, 2019

    Code is working have you tried?

    • Ankita

      July 3, 2019

      not working for me 🙁

  6. Deepak

    February 20, 2019

    I want to run job by Rest API which will trigger start and stop. Is der any wat to start the job and stop the job ?

    • Saurabh Sharma

      March 9, 2020

      You could instead use the API to set a flag in cache or somewhere and use that flag to proceed in the scheduled job.

  7. Rohit Kumar

    January 9, 2019

    Hi

    Thanks for Good Explanation.

    but i have some different requirement instated of passing fixed value to 1 minutes, i need to do it dynamic.
    @Scheduled(cron = “0 */x * * * ?”)

    can its possible to do?

    Thanks in advances

Comments are closed on this article!

Search Tutorials

Spring Batch Tutorial

  • Spring Batch – Java Config
  • Spring Batch – Classifier
  • Spring Batch – Partitioner
  • Spring Batch – Event Listeners
  • Spring Batch – ItemProcessor
  • Spring Batch – Job Scheduling
  • Spring Batch – Quartz
  • Spring Batch – Jdbcjobstore
  • Spring Batch – DI in Quartz Job
  • Spring Batch – FlatFileItemReader
  • Spring Batch – FlatFileItemWriter
  • SB – MultiResourceItemReader
  • Spring Batch – Delete Files
  • Spring Batch – Records Counting
  • Spring Batch – CSV to Database

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces