SoFunction
Updated on 2025-04-05

Summary of the difference between @Scheduled and @Schedules in SpringBoot

Summary of the difference between @Scheduled and @Schedules in SpringBoot

Updated: January 22, 2025 10:32:23 Author: Shangao has its own way to travel
This article mainly introduces the difference between @Scheduled and @Schedules of SpringBoot. The example code is introduced in this article in detail, which has a certain reference learning value for everyone's study or work. If you need it, please follow the editor to learn together.

Detailed analysis of @Scheduled

Detailed explanation of parameters

  • cron: Use Cron expressions to specify complex scheduling modes. The format of the Cron expression is as follows:

    • Seconds (0-59)
    • Minutes (0-59)
    • Hours (0-23)
    • Day (1-31)
    • Month (1-12 or JAN-DEC)
    • Week (0-7 or SUN-SAT, where both 0 and 7 represent Sunday)
    • Year (optional, 1970-2099)

    Each field of a Cron expression can be a specific value, range, list, or wildcard character (*). For example:

    • "0 0 12 * * ?"It means 12 noon every day.
    • "0 15 10 ? * MON-FRI"It means that it will be implemented from Monday to Friday at 10:15 am.
    • "0 0/5 * * * ?"It means that it is executed every 5 minutes.
    • "0 0 12 1 * ?"It means that it will be executed at 12 noon on the first day of each month.
  • fixedRate: Specifies that tasks are repeated at a fixed rate, starting from the beginning of the previous task. It does not wait for the previous task to complete, so if the task execution time exceeds the set time interval, overlapping task instances may be running.

  • fixedDelay: Similar tofixedRate, but it is the time benchmark for the completion of the previous task as the next task starts. This method ensures that only one task instance is running at a time, provided that the task execution time is shorter than the delay time.

  • initialDelay: Time to wait before the first execution (milliseconds). This parameter is usually the same asfixedRateorfixedDelayUse together to set the delay before the first execution.

  • zone: Define the time zone, the default time zone of the system is the default time zone. If your application needs to run in different regions around the world, it may be important to specify the time zone clearly.

How to choose Cron expressions, fixedRate, fixedDelay, initialDelay

  • If you need a very specific scheduling mode, such as performing a task at 2 a.m. every day, you should choose a Cron expression.
  • If you want the task to be repeated at a fixed rate, no matter how much time each execution takes, you should choosefixedRate
  • If you want to wait for a fixed time after the previous task is completely finished before starting the next task,fixedDelayIt's a better choice.
  • If you need to set the delay for the first execution, you can addinitialDelayParameters into your scheduling configuration.

Sample code

import ;
import ;

@Component
public class ScheduledTasks {

    // Execute at 12 noon every day (Shanghai time zone)    @Scheduled(cron = "0 0 12 * * ?", zone = "Asia/Shanghai")
    public void scheduledTaskUsingCron() {
        ("Scheduled task using cron at Asia/Shanghai timezone.");
    }

    // Execute every 5 seconds, wait 2 seconds before the first execution    @Scheduled(fixedRate = 5000, initialDelay = 2000)
    public void scheduledTaskWithFixedRate() {
        ("Scheduled task with fixed rate.");
    }

    // Wait for 3 seconds after the last task is completed before executing the next time    @Scheduled(fixedDelay = 3000)
    public void scheduledTaskWithFixedDelay() {
        ("Scheduled task with fixed delay.");
    }
}

Detailed analysis of @Schedules

@SchedulesMultiple allowed@ScheduledCombining the annotations together to set up multiple different scheduling strategies for the same method. This is very useful for methods that need to be triggered at multiple different time points or conditions.

Sample code

import ;
import ;
import ;

@Component
public class MultipleScheduledTasks {

    // Perform at 12 noon every day and every 5 seconds    @Schedules({
        @Scheduled(cron = "0 0 12 * * ?"),
        @Scheduled(fixedRate = 5000)
    })
    public void multipleScheduledTasks() {
        ("Multiple scheduled tasks.");
    }
}

Enable and manage timing tasks

For these annotations to take effect, you need to make sure that your Spring app has enabled support for them. This can be added on the configuration class@EnableSchedulingTo achieve:

import ;
import ;

@Configuration
@EnableScheduling
public class SchedulingConfig {
    //Configuration class content}

Custom TaskScheduler

For more complex requirements, such as adjusting the thread pool size or setting thread name prefix, you can customize itTaskSchedulerTo configure. Spring provides several built-in scheduler implementations, such asThreadPoolTaskSchedulerandConcurrentTaskScheduler

Sample code

import ;
import ;
import ;

@Configuration
public class SchedulerConfig {

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        (10); // Set the thread pool size        ("MyScheduledTask-");
        (t -> {
            ("Error occurred in scheduled task: " + ());
        });
        (true);
        (60);
        return taskScheduler;
    }
}

Error handling

When a scheduled task throws an exception, Spring logs the error log by default, but the task itself is not cancelled. If you want to change this behavior, you can useDelegatingErrorHandlingRunnableOr directly inThreadPoolTaskSchedulerSet the error handler (as shown in the above example).

Custom error handling logic

You can create your own error handler to catch and handle exceptions:

import ;
import ;
import ;
import ;
import ;

import ;

@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        (2);
        (5);
        (100);
        ("Async-");
        ();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                // Custom exception handling logic                ("Exception in async task: " + ());
            }
        };
    }
}

Best Practices

  • Avoid long-running tasks: Try not to let scheduled tasks execute for too long, as they may block the execution of other tasks. If the task is likely to run for a long time, consider splitting it into smaller parts, or using asynchronous processing.

  • Task conflict management: When usedfixedRateWhen  , be careful that tasks may overlap. If the task execution time may exceed the interval, you should choosefixedDelayTo avoid this situation.

  • Resource Cleanup: Ensure that any acquired resources, such as database connections or file handles, are properly released at the end of the task.

  • Monitoring and alarm: Establish appropriate monitoring and alarm mechanisms so that you can receive notifications and take actions in a timely manner when the task fails. You can use the health check endpoints provided by Spring Boot Actuator, or integrate third-party monitoring tools such as Prometheus, Grafana, etc.

  • Idepotency design: Ensure that task logic is idempotent, that is, performing the same task multiple times will not lead to inconsistent results. This is especially important in distributed environments.

  • Logging: Add detailed logging for each task, including task start time and end time, so as to track task execution.

  • test: Write unit tests and integration tests to verify that the behavior of the timing tasks is as expected. Dependency services can be simulated using Mockito or other testing frameworks.

  • Issues with multi-instance deployment: In the case of multi-instance deployment, all instances will attempt to perform the same timing tasks, which may lead to data race or repeated execution. One solution is to use distributed locks, such as RedLock provided by Redisson, to ensure that only one instance performs a specific task at the same time.

  • Performance optimization: For timed tasks in high concurrency scenarios, the size of the thread pool and the execution frequency of the task should be evaluated to avoid resource exhaustion due to excessive tasks being started simultaneously. The stability and response speed of the system can be improved through current limiting, queue management and asynchronous processing.

Handle FAQs in timing tasks

  • The task did not perform as expected: Check the log to determine if there are any exceptions or error messages. Ensure that the task method is non-static and not modified by final. confirm@EnableSchedulingIt has been enabled correctly. Also, check if there are other factors that prevent tasks from being executed, such as network latency or dependent services unavailable.

  • The task execution order is confusing: If you have multiple tasks executed almost simultaneously, you may experience a confusing execution order. Make sure you understandfixedRateandfixedDelayThe difference and choose the right way according to your needs. Furthermore, the possibility of conflict can be reduced by increasing the minimum interval between tasks.

  • Issues with multi-instance deployment: In the case of multi-instance deployment, all instances will attempt to perform the same timing task. To solve this problem, distributed locking mechanisms such as Redis-based locking or Zookeeper temporary nodes can be introduced to ensure that only one instance performs the task at the same time.

  • Long-running tasks: Try not to let scheduled tasks execute for too long, as they may block the execution of other tasks. If the task is likely to run for a long time, consider splitting it into smaller parts, or using asynchronous processing, such as distributing tasks through message queues (MQ).

  • Time zone issues: Make sure your application handles time zone differences correctly, especially when running around the world. Can be in@ScheduledExplanatory specification in the annotationzoneParameters, or uniformly configure the default time zone throughout the application.

Case Study

Suppose you are developing an e-commerce platform that needs to generate the previous day's sales report at 2 a.m. every day. You can use@ScheduledAnnotation to arrange this task:

import ;
import ;

@Service
public class DailyReportService {

    @Scheduled(cron = "0 0 2 * * ?", zone = "Asia/Shanghai")
    public void generateDailySalesReport() {
        // Execute the logic of generating sales reports        ("Generating daily sales report at Asia/Shanghai timezone.");
    }
}

In addition, you can also combine the above best practices to enhance the reliability of your tasks, such as:

  • Ensure that the task is idempotent, even if the task is repeated for some reason, it will not affect the result.
  • Add detailed logging to help track the execution of tasks.
  • Implement error handling logic to ensure that even if an exception occurs, it can be properly handled.
  • If the platform has multiple instances deployed, consider using distributed locks to prevent multiple instances from generating reports simultaneously.

This is the end of this article about the difference between @Scheduled and @Schedules of SpringBoot. For more related SpringBoot @Scheduled and @Schedules, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • SpringBoot
  • @Scheduled
  • @Schedules

Related Articles

  • Interpretation of Java annotations @Data and @ToString(callSuper=true)

    When using the @Data annotation of the Lombok library, if the subclass does not indicate that it contains the parent class attribute through @ToString(callSuper=true), the toString() method only prints the subclass attributes. Solution: 1. The subclass overrides the toString method; 2. The subclass uses @Data and @ToString(callSuper=true), and the parent class should also use @Data.
    2024-11-11
  • Detailed explanation of static code blocks, construction code blocks, and construction methods in java

    Below, the editor will bring you a detailed explanation of static code blocks, construction code blocks, and construction methods in Java. The editor thinks it's very good, and I'm sharing it with you now. Let me give you a reference. Let's take a look with the editor
    2016-03-03
  • metershpere implementation calls methods in custom jar package

    In MeterSphere interface testing, facing complex situations such as multi-layer loop logic and logical judgment, it is often confusing to write test cases directly. This article introduces a method to simplify this process: first use IDEA to create a Maven project, write the required logic and generate a jar package; then upload this jar package in MeterSphere
    2024-10-10
  • Solution to the slow first access after Spring boot application is started

    This article mainly introduces the solution that the Spring boot application is slow for the first time after it is launched. It has good reference value and hopes it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2021-06-06
  • Detailed explanation of Java annotation @Override annotation

    This article mainly introduces relevant information about the @Override annotation of Java annotations. @Override is an annotation in Java, indicating that a method is overridden (Override) the method in the parent class. The code introduced in the article is very detailed. Friends who need it can refer to it.
    2023-11-11
  • Extended implementation of source code parsing in mybatis

    This article mainly introduces you the relevant information about the extension implementation in mybatis. The example code is introduced in this article in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2019-01-01
  • JPA multi-data source distributed transaction processing solution

    This article mainly introduces two transaction solutions for JPA multi-data source distributed transaction processing. Friends in need can refer to it for reference. I hope it will be helpful. I wish you more progress and get promoted as soon as possible to get a salary increase as soon as possible.
    2022-02-02
  • Detailed explanation of SpringBoot asynchronous method to catch exceptions

    This article mainly introduces SpringBoot asynchronous method to catch exceptions in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.
    2019-09-09
  • Overview of ArrayList class and common methods for basic Java learning

    This article mainly introduces you to the overview of the ArrayList class in Java, commonly used methods, storing strings and traversing them. The sample code in the article is explained in detail. Interested friends can learn about it.
    2022-08-08
  • How to implement international configuration of springboot

    This article mainly introduces how springboot can achieve international configuration, which has good reference value and hopes will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2023-06-06

Latest Comments