Skip to content

Support Kotlin suspending functions with @Scheduled #28515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions spring-context/spring-context.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ dependencies {
optional("org.apache-extras.beanshell:bsh")
optional("org.hibernate:hibernate-validator")
optional("org.jetbrains.kotlin:kotlin-reflect")
optional("org.jetbrains.kotlinx:kotlinx-coroutines-core")
optional("org.jetbrains.kotlin:kotlin-stdlib")
optional("org.reactivestreams:reactive-streams")
testImplementation(testFixtures(project(":spring-aop")))
testImplementation(testFixtures(project(":spring-beans")))
testImplementation(testFixtures(project(":spring-core")))
testImplementation(project(":spring-core-test"))
testImplementation("io.projectreactor:reactor-core")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
testImplementation("org.apache.groovy:groovy-jsr223")
testImplementation("org.apache.groovy:groovy-xml")
testImplementation("org.apache.commons:commons-pool2")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import org.springframework.context.ApplicationListener;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.KotlinDetector;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotatedElementUtils;
Expand Down Expand Up @@ -529,7 +530,12 @@ protected void processScheduled(Scheduled scheduled, Method method, Object bean)
* @see ScheduledMethodRunnable#ScheduledMethodRunnable(Object, Method)
*/
protected Runnable createRunnable(Object target, Method method) {
Assert.isTrue(method.getParameterCount() == 0, "Only no-arg methods may be annotated with @Scheduled");
if (KotlinDetector.isKotlinPresent() && KotlinDetector.isSuspendingFunction(method)) {
// add support for suspend function
Assert.isTrue(method.getParameterCount() == 0||method.getParameterCount()==1, "Only suspend methods or no-arg methods may be annotated with @Scheduled");
} else {
Assert.isTrue(method.getParameterCount() == 0, "Only no-arg methods may be annotated with @Scheduled");
}
Method invocableMethod = AopUtils.selectInvocableMethod(method, target.getClass());
return new ScheduledMethodRunnable(target, invocableMethod);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,39 @@

package org.springframework.scheduling.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.springframework.core.CoroutinesUtils;
import org.springframework.core.KotlinDetector;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;

import org.springframework.util.ReflectionUtils;

/**
* Variant of {@link MethodInvokingRunnable} meant to be used for processing
* of no-arg scheduled methods. Propagates user exceptions to the caller,
* assuming that an error strategy for Runnables is in place.
*
* @author Juergen Hoeller
* @since 3.0.6
* @see org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor
* @since 3.0.6
*/
public class ScheduledMethodRunnable implements Runnable {

private final Object target;

private final Method method;

private static final Log logger = LogFactory.getLog(ScheduledMethodRunnable.class);

/**
* Create a {@code ScheduledMethodRunnable} for the given target instance,
* calling the specified method.
*
* @param target the target instance to call the method on
* @param method the target method to call
*/
Expand All @@ -52,7 +60,8 @@ public ScheduledMethodRunnable(Object target, Method method) {
/**
* Create a {@code ScheduledMethodRunnable} for the given target instance,
* calling the specified method by name.
* @param target the target instance to call the method on
*
* @param target the target instance to call the method on
* @param methodName the name of the target method
* @throws NoSuchMethodException if the specified method does not exist
*/
Expand Down Expand Up @@ -81,12 +90,35 @@ public Method getMethod() {
public void run() {
try {
ReflectionUtils.makeAccessible(this.method);
this.method.invoke(this.target);
}
catch (InvocationTargetException ex) {

if (KotlinDetector.isKotlinPresent() && KotlinDetector.isSuspendingFunction(method)) {
CoroutinesUtils.invokeSuspendingFunction(method, target).subscribe(new Subscriber<Object>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}

@Override
public void onNext(Object o) {

}

@Override
public void onError(Throwable t) {
logger.error("task run failed", t);
}

@Override
public void onComplete() {

}
});
} else {
this.method.invoke(this.target);
}
} catch (InvocationTargetException ex) {
ReflectionUtils.rethrowRuntimeException(ex.getTargetException());
}
catch (IllegalAccessException ex) {
} catch (IllegalAccessException ex) {
throw new UndeclaredThrowableException(ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import org.springframework.core.annotation.AliasFor;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTaskHolder;
Expand Down Expand Up @@ -725,6 +726,17 @@ void nonEmptyParamList() {
context::refresh);
}

@Test
void suspendFunction() throws InterruptedException {
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(SuspendFunctionTest.class);
BeanDefinition testScheduleDefinition = new RootBeanDefinition(ThreadPoolTaskScheduler.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.registerBeanDefinition("scheduler", testScheduleDefinition);
context.refresh();
Thread.sleep(6000);
}

static class FixedDelay {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.springframework.scheduling.annotation

import org.springframework.stereotype.Component

@Component

class SuspendFunctionTest {

@Scheduled(fixedRate = 200)
suspend fun test() {
println("as")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ public static Publisher<?> invokeSuspendingFunction(Method method, Object target
}

private static Object[] getSuspendedFunctionArgs(Object target, Object... args) {
// add support for suspend @Scheduled
if (args.length == 0) {
return new Object[]{target};
}
Object[] functionArgs = new Object[args.length];
functionArgs[0] = target;
System.arraycopy(args, 0, functionArgs, 1, args.length - 1);
Expand Down