How to work with Spring Scheduler

Spring Framework provides a mechanism for scheduling purpose: Spring Scheduler. The tutorial will introduce about how to schedule tasks with Spring.

I. Technology for Spring Scheduler tutorial

– Java 1.8
– Maven: 3.3.9
– Editor: Spring Tool Suite – Version 3.7.3.RELEASE
– Spring Boot: Version: 3.8.0.RELEASE

II. Overview
1. Structure of project

spring-scheduler-structure-of-project

2. Step to Do

– Create Spring Boot project
– Create Create Scheduler Task
– Enable Spring Scheduler
– Run & Check result

III. Practices
1. Create Spring Boot project

Open Spring Tool Suite, on main menu, Choose File->New->Spring Starter Project.
Input needed information about project as below images:

spring-scheduler-input-project-info-2

Press Next button then press Finish. Spring Boot project is created.

2. Create Create Scheduler Task

Create a simple component class with 3 scheduled tasks defined by 3 methods:
– @Scheduled(fixedRate = 2000)
public void timeReport(): the method will be invoked each 2 seconds
– @Scheduled(initialDelay=1000, fixedRate = 2000)
public void initDelayTimeReport(): the method will be delay 1 second & will be invoked each 2 seconds after the first time
– @Scheduled(cron = “*/5 * * * * *”)
public void cronTimeReport(): using cron-expression for define a scheduled task that will be invoked for each 5 seconds.

– @Scheduled: An annotation that marks a method to be scheduled. Exactly one of the cron(), fixedDelay(), or fixedRate() attributes must be specified.

Code details:

3. Enable Spring Scheduler

Using @EnableScheduling in main Spring class: Enables Spring’s scheduled task execution capability, similar to functionality found in Spring’s XML namespace.

4. Run & Check result

– Compile sourcecode:
clean install

– Run project with Spring mode: Spring Boot App.
– Log:

IV. Source code

Spring-Scheduler

By JavaSampleApproach | August 21, 2016.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*