# 7.8. 任务执行与调度

###

在上下文中没有`Executor`bean 的情况下，Spring Boot 自动配置一个具有合理的默认值的`ThreadPoolTaskExecutor`，这些默认值可以自动关联到异步任务执行 ( `@EnableAsync`) 和 Spring MVC 异步请求处理。

如果您在上下文中定义了自定义`Executor`，则常规任务执行（即`@EnableAsync`）将透明地使用它，但配置不会支持 Spring MVC ，因为它需要对`AsyncTaskExecutor`进行实现（名为`applicationTaskExecutor`）。根据您的目标安排，您可以将您的`Executor`更改为 `ThreadPoolTaskExecutor`或定义 `ThreadPoolTaskExecutor`和`AsyncConfigurer`包装自定义的`Executor`。自动配置`TaskExecutorBuilder`允许您轻松创建实例来重现自动配置默认执行的操作。

线程池使用8个核心线程，可以根据负载增长和收缩。这些默认设置可以使用命名空间进行微调`spring.task.execution`，如以下示例所示：

```
spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s
```

这将线程池更改为使用有界队列，以便当队列已满（100 个任务）时，线程池增加到最多 16 个线程。由于线程在空闲 10 秒（而不是默认情况下为 60 秒）时被回收，因此池的收缩更具侵略性。

如果需要与计划的任务执行相关联（例如使用`@EnableScheduling`），也可以自动配置`ThreadPoolTaskScheduler`。线程池默认使用一个线程，可以使用命名空间`spring.task.scheduling`微调其设置，如下例所示：

```
spring.task.scheduling.thread-name-prefix=scheduling-
spring.task.scheduling.pool.size=2
```

如果需要创建自定义执行程序或调度程序，则`TaskExecutorBuilder`bean 和`TaskSchedulerBuilder`bean 在上下文中都可用。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-boot-can-kao-wen-dang/7.-he-xin-te-xing/7.8.-ren-wu-zhi-xing-yu-diao-du.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
