Close

Spring Framework - @Scheduled and @EnableScheduling Examples

Spring Framework 

@Scheduled marks a method to be scheduled per provided fixedDelay, fixedRate or cron parameters.

package com.logicbig.example;

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 java.time.LocalTime;

public class ScheduledExample {

public static void main (String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);

MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
bean.runTask();
System.out.println("call MyBean#runTask() returned");

//exit after 5 secs
Thread.sleep(5000);
System.exit(0);
}

@EnableScheduling
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

private static class MyBean {

@Scheduled(fixedRate = 1000)
public void runTask () {
System.out.printf("Running scheduled task " +
" thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());

try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}

Output

calling MyBean#runTask() thread: com.logicbig.example.ScheduledExample.main()
Running scheduled task thread: pool-1-thread-1, time: 16:04:31.606
Running scheduled task thread: com.logicbig.example.ScheduledExample.main(), time: 16:04:31.606
call MyBean#runTask() returned
Running scheduled task thread: pool-1-thread-1, time: 16:04:32.557
Running scheduled task thread: pool-1-thread-1, time: 16:04:33.556
Running scheduled task thread: pool-1-thread-1, time: 16:04:34.560
Running scheduled task thread: pool-1-thread-1, time: 16:04:35.551
Running scheduled task thread: pool-1-thread-1, time: 16:04:36.557
INFO: No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
Original Post




package com.logicbig.example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

import java.time.LocalTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScheduledOverrideDefaultExecutorExample {

public static void main (String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
MyBean bean = context.getBean(MyBean.class);
bean.runTask();
System.out.println("call MyBean#runTask() returned");

Thread.sleep(3000);
System.out.println("Shutting down after 3 secs");
ConcurrentTaskExecutor exec = (ConcurrentTaskExecutor) context.getBean("taskExecutor");
ExecutorService es = (ExecutorService) exec.getConcurrentExecutor();
es.shutdownNow();
}

@EnableScheduling
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}

@Bean
public TaskScheduler taskExecutor () {
return new ConcurrentTaskScheduler(
Executors.newScheduledThreadPool(3));
}
}

private static class MyBean {

@Scheduled(fixedDelay = 1000)
public void runTask () {
System.out.printf("task thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}

Output

task thread: pool-1-thread-1, time: 19:24:28.344
task thread: com.logicbig.example.ScheduledOverrideDefaultExecutorExample.main(), time: 19:24:28.344
call MyBean#runTask() returned
task thread: pool-1-thread-1, time: 19:24:29.904
task thread: pool-1-thread-2, time: 19:24:31.413
Shutting down after 3 secs
Original Post




A @Scheduled method cannot return values or accept parameter.

package com.logicbig.example;

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 java.time.LocalTime;

public class ScheduledMethodArgExample {

public static void main (String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);

MyBean bean = context.getBean(MyBean.class);
System.out.printf("calling MyBean#runTask() thread: %s%n",
Thread.currentThread().getName());
String s = bean.runTask("from main");
System.out.println("call MyBean#runTask() returned");
System.out.println("returned value: " + s);
}

@EnableScheduling
@Configuration
public static class MyConfig {
@Bean
public MyBean myBean () {
return new MyBean();
}
}

private static class MyBean {

@Scheduled
public String runTask (String message) {
System.out.printf("task thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
System.out.printf("message: %s%n", message);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
return "return value";
}
}
}

Output

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean' defined in com.logicbig.example.ScheduledMethodArgExample$MyConfig: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method 'runTask': Only no-arg methods may be annotated with @Scheduled
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at com.logicbig.example.ScheduledMethodArgExample.main(ScheduledMethodArgExample.java:20)
... 6 more
Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'runTask': Only no-arg methods may be annotated with @Scheduled
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(ScheduledAnnotationBeanPostProcessor.java:413)
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:283)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1588)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
... 16 more
Original Post




package com.logicbig.example;

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.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.time.LocalTime;

public class SchedulingConfigurerExample {

public static void main (String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);

Thread.sleep(5000);
System.out.println(" -- Exiting application after 5 secs-- ");
System.exit(0);

}

@EnableScheduling
@Configuration
public static class MyConfig implements SchedulingConfigurer {

@Override
public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addFixedDelayTask(() -> {
System.out.println("Running task : "+LocalTime.now());

}, 500);
}
}
}

Output

Running task : 19:24:34.176
Running task : 19:24:34.693
Running task : 19:24:35.205
Running task : 19:24:35.716
Running task : 19:24:36.227
Running task : 19:24:36.738
Running task : 19:24:37.249
Running task : 19:24:37.759
Running task : 19:24:38.261
Running task : 19:24:38.771
-- Exiting application after 5 secs--
INFO: No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
Original Post




See Also