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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Top Gen AI Frameworks for Go in 2026: A Hands-On Comparison
  • Building Multi-Rail Payment Failover to Stop Latency Spikes and Double Debits
  • Three Measured Outcomes of Manually Scaling Fleet in Prod
  • One Identity Unveils Active Roles 8.6 with Enhanced Security and Administration

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Jul. 19, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
16.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook