Spring Boot with Schduler – Example

If you want to see how to integration test, how to test rest api with mock, and  how to just mock , this page is for you

This example is a part of  Spring Boot with all examples

Full Code with Spring Boot 2.2.2.RELEASE:

15_spring-boot-scheduler.zip

What you need for run this:

  • Maven 3
  • Java 8

What the code will do:

  • Show how create scheduler

Explain:

This is the file structure:

Code is in Scheduler1.java, look like this:

package com.surasint.example.scheduler;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class Scheduler1 {

//    @Scheduled(fixedDelay = 1000)
    @Scheduled(fixedDelayString = "${schduler.test1}")
    public void test1(){
        System.out.println("test1");
    }
}

Like 7,8:

  • @Configuration tells Spring that this is a Spring bean class
  • @EnableScheduling tell Srping that this class is a scheduler

Line 11 & 12:

  • @Scheduled(fixedDelay = 1000) : tells Spring that this method will run every 1 second
  • @Scheduled(fixedDelayString = “${schduler.test1}”) : tells Spring tat this method will run as value of schduler.test1 in the application.properties file

Try:

run this in console:

mvn clean package

Then run this to start (this will use the default profile which is “local”):

mvn clean spring-boot:run

You should see something like this:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

.....
.....
2017-12-12 22:03:04.243  INFO 260 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.Annotation
ConfigEmbeddedWebApplicationContext@7595f8d7: startup date [Tue Dec 12 22:03:01 CET 2017]; root of context hierarchy

Then you should see this in the log

2020-01-06 14:50:05.177 INFO 9092 --- [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
test1
2020-01-06 14:50:05.221 INFO 9092 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-01-06 14:50:05.225 INFO 9092 --- [ main] com.surasint.example.MyApplication : Started MyApplication in 1.989 seconds (JVM running for 2.53)
test1
2020-01-06 14:50:12.299 INFO 9092 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler : Shutting down ExecutorService 'taskScheduler'
2020-01-06 14:50:12.301 INFO 9092 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'