`SimpleAsyncTaskScheduler` does not apply its `TaskDecorator` to fixed-delay tasks

クローズ 初心者向け
#37,612 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
82/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
java, spring
領域
backend

調査の方向性

SimpleAsyncTaskScheduler、特に taskOnSchedulerThread と execute から始め、固定遅延タスクとその他のスケジュール済みタスクの扱いを比較してください。SimpleAsyncTaskSchedulerTests を実行し、issue に記載された固定遅延デコレーターのテストを確認してください。固定遅延タスクにデコレーターが適用され、テストが成功すれば完了です。

索引モデルが issue の本文から書いたものです。

説明

in: core status: waiting-for-triage

SimpleAsyncTaskScheduler runs fixed-delay tasks on its scheduler thread (#31334), wrapped by taskOnSchedulerThread, which adds the error handler but not the TaskDecorator. One-time, fixed-rate and trigger tasks go through execute, where the decorator is applied. ThreadPoolTaskScheduler decorates all of them, fixed-delay included (decorateTask).

So a @Scheduled(fixedDelay = …) method runs without whatever the decorator sets up (MDC, security or context propagation), and nothing warns about it. With Spring Boot it changes when virtual threads are enabled: Boot then creates a SimpleAsyncTaskScheduler instead of a ThreadPoolTaskScheduler, passing the application's TaskDecorator beans to either of them.

The Javadoc of setTaskDecorator says the decorator is "applied to any Runnable about to be executed". The class Javadoc says that fixed-delay tasks run on the single scheduler thread, but not that they skip the decorator.

Affects 7.0.10; the code is the same on main.

Reproducer

Spring Framework 7.0.10 on JDK 25: java -cp <spring-context and its dependencies> FixedDelayTaskDecorator.java

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;

public class FixedDelayTaskDecorator {

	// Set by the TaskDecorator around each task, as a context-propagating decorator would do
	static final ThreadLocal<Boolean> decorated = ThreadLocal.withInitial(() -> false);

	static final Map<String, Boolean> results = new ConcurrentHashMap<>();

	static final CountDownLatch latch = new CountDownLatch(2);


	public static void main(String[] args) throws InterruptedException {
		try (var context = new AnnotationConfigApplicationContext(Config.class)) {
			latch.await(5, TimeUnit.SECONDS);
			System.out.println("fixedRate  task decorated: " + results.get("fixedRate"));
			System.out.println("fixedDelay task decorated: " + results.get("fixedDelay"));
		}
	}


	@Configuration
	@EnableScheduling
	static class Config {

		@Bean
		SimpleAsyncTaskScheduler taskScheduler() {
			SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler();
			scheduler.setVirtualThreads(true);
			scheduler.setTaskDecorator(task -> () -> {
				decorated.set(true);
				try {
					task.run();
				}
				finally {
					decorated.remove();
				}
			});
			return scheduler;
		}

		@Bean
		Tasks tasks() {
			return new Tasks();
		}
	}


	static class Tasks {

		@Scheduled(fixedRate = 100)
		void fixedRate() {
			record("fixedRate");
		}

		@Scheduled(fixedDelay = 100)
		void fixedDelay() {
			record("fixedDelay");
		}

		private static void record(String task) {
			if (results.putIfAbsent(task, decorated.get()) == null) {
				latch.countDown();
			}
		}
	}

}

Output:

fixedRate  task decorated: true
fixedDelay task decorated: false

With a ThreadPoolTaskScheduler instead (and no setVirtualThreads), both lines print true.

Possible fix

Keep a reference to the decorator and apply it in taskOnSchedulerThread, around the error handling, as execute does:

--- a/SimpleAsyncTaskScheduler.java
+++ b/SimpleAsyncTaskScheduler.java
@@ -37,6 +37,7 @@
 import org.springframework.context.SmartLifecycle;
 import org.springframework.context.event.ContextClosedEvent;
 import org.springframework.core.task.SimpleAsyncTaskExecutor;
+import org.springframework.core.task.TaskDecorator;
 import org.springframework.core.task.TaskRejectedException;
 import org.springframework.scheduling.TaskScheduler;
 import org.springframework.scheduling.Trigger;
@@ -124,6 +125,8 @@
 
 	private @Nullable ErrorHandler errorHandler;
 
+	private @Nullable TaskDecorator taskDecorator;
+
 	private Clock clock = Clock.systemDefaultZone();
 
 	private int phase = DEFAULT_PHASE;
@@ -142,6 +145,12 @@
 		this.errorHandler = errorHandler;
 	}
 
+	@Override
+	public void setTaskDecorator(TaskDecorator taskDecorator) {
+		super.setTaskDecorator(taskDecorator);
+		this.taskDecorator = taskDecorator;
+	}
+
 	/**
 	 * Set the clock to use for scheduling purposes.
 	 * <p>The default clock is the system clock for the default time zone.
@@ -230,8 +239,9 @@
 	}
 
 	private Runnable taskOnSchedulerThread(Runnable task) {
-		return new DelegatingErrorHandlingRunnable(task,
+		Runnable taskToUse = new DelegatingErrorHandlingRunnable(task,
 				(this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true)));
+		return (this.taskDecorator != null ? this.taskDecorator.decorate(taskToUse) : taskToUse);
 	}
 
 	private Runnable scheduledTask(Runnable task) {

With that change on top of 7.0.10, the reproducer prints true twice, and SimpleAsyncTaskSchedulerTests passes together with this test, which fails without it (its buildExecutor() already sets a decorator that flags taskRun):

	@Test
	void scheduleWithFixedDelay() {
		TestTask task = new TestTask(this.testName, 3);
		Future<?> future = scheduler.scheduleWithFixedDelay(task, Duration.ofMillis(10));
		await(task);
		future.cancel(true);
		assertThat(taskRun.get()).isTrue();
	}
主要言語
Java
スター
60.3k
フォーク
38.7k
平均マージ
1日 12時間
マージ済み PR(30日)
30

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

spring-projects/spring-framework のほかの issue

spring-projects/spring-framework の issue をすべて見る

似ている issue

Java の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。