segunda-feira, 19 de fevereiro de 2018

Spring Boot – Scheduling Recipe

Spring Boot Scheduling Recipe
To create a scheduled task in Spring Boot you can follow the following steps
1. Create a Spring Boot Project include in the pom.xml file the following dependency
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
2 Create a scheduled task
Now that you’ve set up your project, you can create a scheduled task.
The Scheduled annotation defines when a particular method runs.
NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation.
There are other options, like fixedDelay, which specifies the interval between invocations measured from the completion of the task.
You can also use @Scheduled(cron=”. . .”) expressions for more sophisticated task scheduling. Please refer to cron expression for details.
package hello;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(“HH:mm:ss”);
//@Scheduled(fixedRate = 5000)
@Scheduled(cron=”${process.scheduled.start}”)
public void reportCurrentTime() {
log.info(“The time is now {}”, dateFormat.format(new Date()));
}
}
3. Enable Scheduling
Although scheduled tasks can be embedded in web apps and WAR files,
the simpler approach demonstrated below creates a standalone application.
You package everything in a single, executable JAR file, driven by a good old Java main() method.
@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}

Nenhum comentário:

Postar um comentário