DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Distributed Task Synchronization: Leveraging ShedLock in Spring
  • External Task Client Implementation in Camunda With Spring Boot Application
  • Clustered Quartz Scheduler With Spring Boot and MongoDB
  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot

Trending

  • Measuring the Impact of AI on Software Engineering Productivity
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Agentic AI for Automated Application Security and Vulnerability Management
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  1. DZone
  2. Coding
  3. Frameworks
  4. A Guide to Spring Boot Scheduling

A Guide to Spring Boot Scheduling

if you want your application to perform some task after a fixed interval or based on some schedule, Spring Boot Scheduling can be a handy feature.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Jul. 19, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
16.0K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Boot Scheduling is a handy feature that allows us to schedule jobs in our Spring Boot applications. For example, if you want your application to perform some task after a fixed interval or based on some schedule, this feature can be used.

It also works on the principle of a typical cron job. However, since we can handle it within our application, it becomes relatively easy to perform complex tasks with plain Java code.

If you would like to know more about Spring Boot in general, we have a detailed guide on Spring Boot Microservices. However, if you are looking for just a quick intro to Spring Boot Scheduling, then you can simply continue with this post where we set up scheduling in a dummy Spring Boot application.

So let’s start with the process of setting up Spring Boot Scheduler.

1 – The @EnableScheduling Annotation

The first thing required to use the scheduler is to annotate the main class using @EnableScheduling annotation.


Java
 
@SpringBootApplication
@EnableScheduling
public class SpringBootSchedulingApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSchedulingApplication.class, args);
    }

}


This annotation basically enables the support for scheduling functionality in our application.

2 – Scheduling a Task at Fixed Delay

The first option available is to schedule a task at a fixed delay. This can be done by annotating a method with @Scheduled annotation as below:


Java
 
package com.progressivecoder.springbootscheduling;

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelay = 1000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed delay: " + System.currentTimeMillis() / 1000);
    }
}



In the fixed delay option, the duration between the end of the previous task and the beginning of the new task is fixed. In the above example, it is 1000 milliseconds or 1 second. Also, the new task always waits for the previous one to finish.

This behavior is particularly useful when it is imperative that a new task starts only after the previous ends.

3 – Scheduling a Task at Fixed Rate

If we want to have parallel execution of tasks, we need to use the fixed rate parameter. However, to make it really parallel, we also need to use @Async annotation. This will make each task independent of the other tasks.


Java
 
package com.progressivecoder.springbootscheduling;

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

@Component
@EnableAsync
public class ScheduledTask {

    @Async
    @Scheduled(fixedRate = 1000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed rate: " + System.currentTimeMillis() / 1000);
    }
}



While using the fixed-rate option, we need to be careful not to exceed the size of the memory or the thread pool. If the tasks are long-running, this might lead to Out of Memory Exceptions.

4 – Schedule a Task With Initial Delay

We also have the option of scheduling tasks with an initial delay. This can be done as follows:


Java
 
package com.progressivecoder.springbootscheduling;

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelay = 1000, initialDelay = 4000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed delay: " + System.currentTimeMillis() / 1000);
    }
}



By using the initial delay parameter, we ensure that the first execution of the task happens after the initial delay time.

5 – Schedule Task Using Cron Expressions

We get a lot of flexibility while using @Scheduled annotation. As an example, we can also use regular cron expressions.


Java
 
package com.progressivecoder.springbootscheduling;

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

@Component
public class ScheduledTask {

    @Scheduled(cron = "* * * ? * *")
    public void scheduleTask() {
        System.out.println("Printing hello after cron delay: " + System.currentTimeMillis() / 1000);
    }
}



Here, the cron expression “* * * ? * *” signifies execution every second. In other words, the task will be executed every second based on the server time.

6 – Parameterize the Spring Boot Scheduling

While you can simply hard-code the schedule value, it could also be useful to be parameterize the schedules. That way, you can change the schedule of a particular task without worrying about recompiling the code.

This can be easily done by using the fixedDelayString, fixedRateString, and cron parameters. See an example below:


Java
 
package com.progressivecoder.springbootscheduling;

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
    public void scheduleTask() {
        System.out.println("Printing hello after cron delay: " + System.currentTimeMillis() / 1000);
    }
}



The variable ${fixedDelay.in.milliseconds} can be set up as part of environment variables to your Spring Boot application.


With this, we have looked at the various options provided by the Spring Boot Scheduling mechanism. Basically, by using this feature, it becomes very easy to schedule periodic tasks as part of your application itself. You can also find more details about this at the official Spring site.

If you have any comments or queries about this, please do mention them in the comments section below.

Spring Framework Spring Boot job scheduling Task (computing)

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Task Synchronization: Leveraging ShedLock in Spring
  • External Task Client Implementation in Camunda With Spring Boot Application
  • Clustered Quartz Scheduler With Spring Boot and MongoDB
  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!