The methods annotated with @Scheduled must have void returns and must not have any arguments. This is because of scheduled methods' periodic nature where passing an argument or receiving a return value won't make much sense.
Following example shows that specifying a return value is ignored on @Scheduled method.
Example
The bean
package com.logicbig.example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Component
public class MyBean {
@Scheduled(fixedRate = 1000)
public String runTask() {
System.out.printf("task thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
return "return value";
}
}
Main class
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalTime;
@EnableScheduling
@ComponentScan
@Configuration
public class ScheduledMethodReturnExample {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScheduledMethodReturnExample.class);
}
}
Outputtask thread: pool-1-thread-1, time: 16:58:54.635834500 task thread: pool-1-thread-1, time: 16:58:55.630153400 task thread: pool-1-thread-1, time: 16:58:56.631426100 task thread: pool-1-thread-1, time: 16:58:57.631041600 task thread: pool-1-thread-1, time: 16:58:58.638495100 task thread: pool-1-thread-1, time: 16:58:59.629680900 task thread: pool-1-thread-1, time: 16:59:00.645981300 task thread: pool-1-thread-1, time: 16:59:01.642230 task thread: pool-1-thread-1, time: 16:59:02.634376100 task thread: pool-1-thread-1, time: 16:59:03.694373300 task thread: pool-1-thread-1, time: 16:59:04.637092300 .....................
Version older than 4.3.0.RELEASE
Spring's version older than 4.3.0.RELEASE will throw the following error if we declare a return type other than void. For example if we try to run above code with Version 4.2.9.RELEASE, we will have following error:
Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'runTask': Only void-returning methods may be annotated with @Scheduled
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 4.3.0.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|