HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Spring boot @Scheduled annotation example

By Lokesh Gupta | Filed Under: Spring Boot

To schedule job in spring boot application to run periodically, spring boot provides @EnableScheduling and @Scheduled annotations. Lets learn to use Spring boot @Scheduled annotation.

Let’s say you want to run job at every 10 seconds interval. You can achieve this job scheduling in below steps:

1. Add @EnableScheduling to Spring Boot Application class

Add @EnableScheduling annotation to your spring boot application class. @EnableScheduling is a Spring Context module annotation. It internally imports the SchedulingConfiguration via the @Import(SchedulingConfiguration.class) instruction

@SpringBootApplication
@EnableScheduling
public class SpringBootWebApplication {
	
}

Read More : 4 ways to schedule tasks in Spring

2. Add Spring boot @Scheduled annotations to methods

Now you can add @Scheduled annotations on methods which you want to schedule. Only condition is that methods should be without arguments.

ScheduledAnnotationBeanPostProcessor that will be created by the imported SchedulingConfiguration scans all declared beans for the presence of the @Scheduled annotations.

For every annotated method without arguments, the appropriate executor thread pool will be created. This thread pool will manage the scheduled invocation of the annotated method.

2.1. Schedule task at fixed rate

Execute a task at a fixed interval of time:

@Scheduled(initialDelay = 1000, fixedRate = 10000)
public void run() {
	logger.info("Current time is :: " + Calendar.getInstance().getTime());
}

Now observe the output in console:

2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017
2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017
2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017
2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017
2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017

2.2. Schedule task at fixed delay

Configure a task to run after a fixed delay. In given example, the duration between the end of last execution and the start of next execution is fixed. The task always waits until the previous one is finished.

@Scheduled(fixedDelay = 10000)
public void run() {
	logger.info("Current time is :: " + Calendar.getInstance().getTime());
}

2.3. Spring boot cron job example

@Scheduled annotation is very flexible and may take cron expression as well.

@Scheduled(cron = "0 10 10 10 * ?")
public void run() {
	logger.info("Current time is :: " + Calendar.getInstance().getTime());
}

Drop me your questions on this spring task scheduler annotation example.

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

12
Leave a Reply

This comment form is under antispam protection
6 Comment threads
6 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Daniel

For cron job example, is there a way to get all jobs created ? in order to see which one are created and running in runtime. I think the equivalent in shell command would be: crontab -e

Vote Up0Vote Down  Reply
4 months ago
Lokesh Gupta

Not sure if it is possible.

Vote Up0Vote Down  Reply
4 months ago
Chetan Mahajan

Hi Daniel,

For that you have to go with the quartz implementation and you must have to make it persistent so that you can store the auditing information as well.

Vote Up0Vote Down  Reply
2 months ago
roshan

why ?
what are advantages?
what are drawback ?

Vote Up0Vote Down  Reply
6 months ago
susant kumar

can I create a cron job using this annotation where my application will run on every morning at 6 pm

Vote Up0Vote Down  Reply
6 months ago
Chetan Mahajan

Yes, below is the cron expression for the same:
0 0 6 ? * MON *

Please visit cronmaker.com for any kind of cron expressions.

Vote Up0Vote Down  Reply
2 months ago
Lakshmi Venkateswaran

Hi Lokesh,

Does the scheduler stop/fail due to external reasons like thread pool max size reached etc. I ask this because my scheduler is expected to run indefinitely but it stops unexpectedly.

Regards,
Lakshmi Venkateswaran.

Vote Up0Vote Down  Reply
10 months ago
Lokesh Gupta

Hi Lakshmi, I have used it in one of my application at employer site and it is working since a year without failure at production. I have not faced any such issue. It seems there is some issue with the task it tries to run. Some StackOverflow threads also suggest so.

Can you please review the details of your task or else share if need second opinion.

Vote Up0Vote Down  Reply
10 months ago
YASEEN

How will i be able to disable a schedular in spring boot,when the uses wisheds to stop it.Is there any example code for this.
Kindly help!
Thanks,
Yaseen

Vote Up0Vote Down  Reply
11 months ago
Parekh

Hi Lokesh,

Thanks for this article.

If I have option of running Linux/Unix cronjob and also Spring scheduler. Which one be preferred option to go for? Any pros and cons?

Thanks,
Parekh

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

I will prefer to have Job configuration inside application code, so that it is not machine dependent and a less team to communicate with 🙂 Technically, both will solve the purpose. You have to see pros/cons outside that.

Vote Up0Vote Down  Reply
2 years ago
Parekh

Thanks Lokesh.

Vote Up0Vote Down  Reply
2 years ago

Search Tutorials

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz