Updated September 2, 2023
Table of Contents
- Introduction
- How does it work?
- Scheduling Setup and Time Configuration Methods
- Steps to Implement
- Utilize property file Value
- Conclusion
- FAQs
Introduction to Spring Boot Scheduler
As the name suggests, a scheduler is used to schedule a particular task or activity that we want to execute at a fixed time in a day or at any time; for this mechanism to be implemented in spring boot, we can use the scheduler. In spring boot, we can easily implement a scheduler using annotations; no other configurations are required to make this work in spring boot. Inside the schedule, we can write the logic that we want to execute at the specific time of the day, to mention the time we have to follow the standard given by the spring boot. Here, we will see its internal working and how to specify the time inside the scheduler in the spring boot application.
Syntax
As we know, in spring boot, we have to configure or enable everything before we use it inside the application; this is the same thing with the scheduler. Also, let’s look at the syntax for allowing scheduling and use it inside the program.
@Scheduled(your expression)
public void method_name() {
// logic goes here ..//
}
As you can see in the above syntax, we have used @Scheduled annotation over the method to use scheduling inside the program.
@Scheduled(1000)
public void test() {
// logic here ..//
}
How does Scheduler work in Spring Boot?
We already know that Spring Boot or General scheduler is used to scheduling a task or activity to be executed at a fixed time to perform some logic in the application.
While using the scheduler in Spring Boot, we have two things to be considered while using it.
- The method that annotates with @schedul annotation should not accept any parameter inside it.
- The methods annotated with @schedul annotation should return a void type-in program.
These are two things that need to be kept and mind while using it; otherwise, we will get the error.
Scheduling Setup and Time Configuration Methods
In this section, we will first see the things required to set up a schedule and different ways to provide the time inside it.
Using cron Job
In spring boot, we can schedule an activity using the cron job; this is very flexible and easy to use. Using it, we can specify the different parameters in the expression. This expression lets us initialize the day, month, minute, etc. when we want our task to run. This expression consists of five fields, which should be in the same order.
(minute) (hour) (day-of-month) (month)> (day-of-week) (command)
We can specify our value in the same order; if any fields are missing in the expression, it will throw a runtime exception.
Below is one sample syntax to initialize the cron using the expression, which will execute the task daily at 12:00 PM.
Example
0 12 * * ?
Immediate Scheduled Invocation
The second way is to pass any fixed value inside the scheduler, which will run that scheduler at this field time.
@Scheduled(fixedRate = 1000)
public void test() throws InterruptedException {
// logic goes here ..
}
In the above line of code, we had used fixedRate the attribute o Scheduled in spring boot and assigned it value as ‘1000’ here, so this will invoke the task in the very second when the server starts. Also, there will be no delay between the server’s start and the scheduler’s first run; it will execute the first time immediately when the server is up. If we want to delay, we can use the after attribute of the scheduler for this.
Initial Delay Scheduler
The initial delay in a scheduler represents the time a task waits before its first execution. It ensures the task doesn’t run immediately upon scheduling but starts after the specified delay period. This delay is helpful for scenarios where you want to introduce a delay before the recurring execution of a scheduled task.
To provide an initial delay, we can use the initialDelay attribute of the Scheduled annotation, which will start running the task with this initial delay only.
Example
@Scheduled(fixedDelay = 1000, initialDelay = 5000)
public void test() {
// logic will go here ..//
}
Scheduled Delay Attribute
The @Scheduled annotation in Spring Boot allows you to specify a fixedDelay attribute, which determines the time delay in milliseconds between the completion of one execution of a scheduled method and the start of the next. This ensures a consistent time gap between successive method invocations, regardless of how long each execution takes.
Usage of cron
In Unix-like operating systems, Cron is a job scheduler based on time. It uses a flexible syntax to define schedules for executing tasks at specific times, intervals, or dates. Cron is widely used for automating recurring tasks, such as backups, data processing, and system maintenance, making it a crucial tool for system administrators and developers. Below, see the syntax for using crone in @Scheduled annotation.
Example
@Scheduled(cron="* * * * *")
public void test() {
// logic here .. //
}
Steps to Implement a Scheduler in Spring Boot
The steps that need to be followed to implement the scheduler in the spring boot application which is as follows:
Step: 1
First, we will develop the application using the spring initializer, with all the necessary details to make it run.
Step: 2
We have to enable scheduling in the main application; without this, it will not work, and the task will not execute. To allow the scheduling, we used one annotation @EnableScheduling, which needs to be used in the main class.
Example
@SpringBootApplication
@EnableScheduling
public class SchedularApplication {
public static void main(String[] args) {
SpringApplication.run(SchedularApplication.class, args);
}
}
Step: 3
Now, we are ready to create the method to execute a task at a specific time, create a separate class, and create one method inside it.
Example
@Component
public class SchedulerDemo {
@Scheduled(cron = "0 * 2 * * ?")
public void execute() {
// some operation will go here ..//
// like db update etc
}
}
We have used the cron expression here, but you can use anything as required.
Utilize property file Value
In a Spring Boot application, property files, typically in the form of application.properties or application.yml, are used to externalize configuration values. Placing configuration properties in these files allows you to easily modify the application’s behavior without changing the source code. For example, you can define database connection settings, server ports, logging levels, or any custom configuration values in these files. Spring Boot’s auto-configuration mechanism automatically reads these properties and wires them into your application’s components. This approach makes it easier to manage and maintain the application’s settings without code changes with environment-specific configurations.
Conclusion
By using scheduling in an application, we can execute the task independently and update or create thousands of records in the database, which will not impact the user experience with the application. If you want to trigger a method that will execute some logic automatically, you can go for the scheduler in Spring Boot, which is easy to use and handle.
FAQs
Q1. What are the benefits of using a scheduler in Spring Boot?
Answer:
Using a scheduler in Spring Boot offers several benefits:
- Automated Task Execution: Schedulers automate task execution, reducing manual intervention and ensuring timely completion.
- Improved Efficiency: Scheduled tasks can optimize resource utilization by running at specified intervals or during off-peak hours, enhancing system efficiency.
- Time-Based Actions: Schedulers enable time-based actions, such as sending emails, generating reports, or cleaning up data, making applications more functional and user-friendly.
- Simplified Maintenance: Scheduling tasks within the Spring Boot framework simplifies task management, monitoring, and maintenance, enhancing application reliability.
Q2. How do we handle exceptions in Spring Boot schedulers?
Answer: In Spring Boot schedulers, you can handle exceptions by simply adding a try-catch block within your scheduled task method. If an exception occurs during task execution, it can be caught, logged, and handled appropriately. You can use standard exception-handling techniques such as logging the error, sending notifications, or gracefully handling the exception to prevent it from disrupting the scheduler’s operation. Additionally, you can leverage Spring’s error-handling mechanisms, like @ExceptionHandler, to centralize exception handling for better maintainability and consistency across your application.
Q3. How do I manage concurrent scheduling in Spring Boot?
Answer: To manage concurrent scheduling in Spring Boot, you can use a combination of features like configuring a TaskScheduler bean and using the @Async annotation. By customizing the TaskScheduler bean, you can control the number of threads available for scheduling tasks concurrently. Additionally, annotating your scheduled methods with @Async allows them to be executed in separate threads, achieving concurrent scheduling. This approach ensures that your scheduled tasks run concurrently without blocking the main scheduler thread.
Q4. Can I schedule tasks with parameters using Spring Boot?
Answer: Yes, it is possible to schedule tasks with parameters using Spring Boot. You can create a scheduled method with parameters in the same way as any other Java method. You can provide the necessary arguments when the scheduled method runs according to its schedule. These arguments can come from different sources, such as application properties, databases, or other Spring components. This feature enables you to schedule and execute tasks with adjustable and customizable parameters in your Spring Boot application.
Recommended Articles
We hope that this EDUCBA information on “Spring Boot Scheduler” was beneficial to you. You can view EDUCBA’s recommended articles for more information.