SoFunction
Updated on 2025-04-06

Detailed explanation of the difference between Scheduled and Async in Spring two task scheduling

Introduction to Spring Task Scheduling

Task scheduling is a very common requirement in modern applications. The Spring framework provides two main ways to implement task scheduling:​Scheduled​and​Async​​. In this article, we will introduce in detail the differences and application scenarios of these two methods.

Scheduled Task

​Scheduled​The task is based on Spring​@Scheduled​​Annotated task scheduling method. In this way, you can easily set a timer on a method to allow the method to execute at a specified frequency. The following is the use​@Scheduled​A simple example of annotation:

@Component
public class ScheduledTask {
 
    @Scheduled(cron = "0 * * * * ?") // Perform every minute    public void scheduledTask() {
        ("Scheduled task executed!");
    }
}

In this example,​@Scheduled​​Annotated​cron​The property sets a simple Cron expression to indicate that tasks are executed every minute.

Features of Scheduled Tasks

  • Timing:​​Scheduled​​ Tasks can accurately schedule task execution time according to Cron expressions or fixed delays.
  • Execution order:​​Scheduled​​ Tasks are executed in the set order, which is very useful for tasks that require strict control over the execution order.
  • Repeat execution:​​Scheduled​​ Tasks can be set to the frequency of repeated execution, such as hourly, daily, weekly, etc.

Async Tasks

​Async​​ Tasks are the way Spring provides to execute tasks asynchronously. In this way, you can mark a method asynchronous execution, which Spring will automatically submit to the thread pool for processing. The following is the use​@Async​A simple example of annotation:

@Component
public class AsyncTask {
 
    @Async
    public void asyncTask() {
        ("Async task executed!");
    }
}

Features of Async tasks

  • Non-blocking:​​Async​The task will return immediately after being called and will not block the current thread.
  • Concurrent execution:​​Async​​ Tasks can be executed concurrently in multiple threads, improving application throughput.
  • No order guaranteed:​​Async​​ Tasks do not guarantee the order of execution, because they are executed in different threads.

Compare and choose

Select to use​Scheduled​Or​Async​When you are ​​, you should consider the following factors:

  • Nature of the task: If the task is computationally intensive or requires strict control of the execution order, then​Scheduled​​Maybe more suitable. If it is I/O intensive or there are no strict requirements for the execution order,​Async​​Maybe better.
  • System Performance: If the system needs to handle a large number of concurrent tasks,​Async​​It can improve performance because it can execute tasks concurrently in a thread pool.
  • Timing requirements: If the task needs to be executed regularly, then​Scheduled​​is a better choice.

In summary,​Scheduled​​As suitable for situations where regular execution is required and the order of execution is required, and​Async​​ Suitable for situations where asynchronous execution is required and there is no requirement for the order of execution. In practical applications, choosing the right method according to specific needs can improve the efficiency and performance of the application. In practical applications, Spring's​Scheduled​and​Async​​Annotations are often used for processing asynchronous tasks. Here are a simple example code that demonstrates how to use these two annotations in Spring.

Scheduled Example

​Scheduled​​Annotations are used to perform tasks regularly. Here is a simple timing task example that prints messages every 5 seconds:

import ;
import ;
 
import ;
 
@Component
public class ScheduledTask {
 
    @Scheduled(fixedRate = 5000) // Execute every 5 seconds    public void scheduledTask() {
        ("Scheduled task executed at: " + new Date());
    }
 
}

In this example, the @Scheduled annotation is placed on the method scheduledTask(), which means that the method will be executed at the specified frequency. The fixedRate property specifies the frequency of task execution in milliseconds.

Async Example

The Async annotation is used to declare a method asynchronous execution. Here is a simple asynchronous task example:

import ;
import ;
 
import ;
 
@Component
public class AsyncTask {
 
    @Async
    public Future<String> asyncTask() {
        ("Async task started...");
        // Simulate long-running tasks        try {
            (1000);
        } catch (InterruptedException e) {
            ();
        }
        ("Async task completed.");
        return Future.<String>supplyAsync(() -> "Task completed!").get(); // Return a Future object    }
 
}

In this example, the @Async annotation is placed on the method asyncTask(), which means that the method will be executed asynchronously. The method returns a Future object that allows the result to be retrieved when the task is completed.

Note that methods using @Async annotations must be run in an environment that supports asynchronous execution, such as Spring's @EnableAsync annotations enable asynchronous support. Usually, you need to add the following configuration in the Spring configuration class:

import ;
 
@Configuration
@EnableAsync
public class AppConfig {
 
}

This will enable asynchronous support so that​@Async​​Annotations work properly.

In practice, you may also use it in combination​​@Scheduled​and​@Async​​Annotation, for example, you might have a task that needs to be executed asynchronously at a specific time. Spring framework provides two methods for task scheduling:​Scheduled​and​Async​​. Both methods can be passed​@Scheduled​and​@Async​​Annotations to implement. Below I will introduce the usage and code examples of these two methods in detail.

Scheduled

​@Scheduled​​Annotations are used to create tasks that are executed regularly. It supports a variety of triggers, including fixed rate, fixed delay, and cron expressions. Here is a use​@Scheduled​A simple example of annotations:

import ;
import ;
 
@Component
public class ScheduledTask {
 
    @Scheduled(fixedRate = 1000 * 60 * 10) // Perform every 10 minutes    public void scheduledTask() {
        ("Scheduled task executed!");
    }
 
    @Scheduled(cron = "0 0 12 * * ?") // Perform at 12 noon every day    public void cronTask() {
        ("Cron task executed!");
    }
 
    // Other methods...}

In this example, the @Scheduled annotation is applied to two methods. The first method uses the fixedRate property to set the task to be executed every 10 minutes. The second method uses the ​​cron​​ property to set a cron expression, which means that the task is executed at 12 noon every day.

Async

​​@Async​​ The annotation is used to execute methods asynchronously. When a method is marked as @Async​​, Spring uses AsyncTaskExecutor​ to execute the method without blocking the calling thread. Here is a simple example using the @Async​annotation:

import ;
import ;
 
@Component
public class AsyncTask {
 
    @Async
    public void asyncTask() {
        ("Async task executed in a separate thread!");
    }
 
    // Other methods...}

In this example, the @Async annotation is applied to a method. When this method is called, it will be executed in a separate thread without blocking the calling thread.

Use in combination

You can also use the @Scheduled​​ and the @Async​annotation so that you can perform an asynchronous task periodically. Here is an example of using it in combination:

import ;
import ;
import ;
 
@Component
public class ScheduledAndAsyncTask {
 
    @Scheduled(fixedRate = 1000 * 60 * 10)
    @Async
    public void scheduledAndAsyncTask() {
        ("Scheduled and async task executed in a separate thread!");
    }
 
    // Other methods...}

In this example, the @Scheduled​​ and @Async​annotations are applied to a method at the same time. This means that the task will be executed periodically and asynchronously in a separate thread.

Note that when using @Async annotation, you may need to make sure that you have AsyncTaskExecutor in your application context to perform these asynchronous tasks. Typically, you can enable asynchronous support by configuring the @EnableAsync annotation and provide a TaskExecutor bean.

import ;
import ;
import ;
import ;
 
@Configuration
@EnableAsync
public class AsyncConfiguration {
 
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // Configure thread pool parameters...        return executor;
    }
 
    // Other bean definitions...}

In this configuration class, we create a​ThreadPoolTaskExecutor​and use it as​taskExecutor​bean Register into the Spring application context. In this way, any​@Async​The annotation methods will be in this thread

The above is the detailed explanation of the difference between Scheduled and Async in Spring's two task scheduling and Scheduled Scheduled and Async. For more information about Scheduled Scheduled and Async, please pay attention to my other related articles!