Schedulare task in Spring Boot e Java
Spring Boot ha già tutto per creare task schedulati.
E possiamo usare sia una sintassi simile a CRON che non.
In questo articolo vediamo come fare.
Prima di tutto dobbiamo attivare le schedulazioni:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class CiesApiVpsApplication {
public static void main(String[] args) {
SpringApplication.run(CiesApiVpsApplication.class, args);
}
}
In sostanza dovete aggiungere l'annotazione @EnableScheduling.
Poi creaimo una classe segnata come @Component:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class ScheduleEmail {
@Scheduled(initialDelay = 120000, fixedRate = 120000)
public void execute() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("Current Date and Time: " + dtf.format(now));
}
}
Nell'annotazione @Scheduled abbiamo indicato che il primo task deve essere eseguito dopo 2 minuti; i successivi sempre ogni due minuti.
Se volessimo usare CRON:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Component
public class ScheduleEmail {
@Scheduled(cron = "0 */2 * ? * *")
public void execute() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("Current Date and Time: " + dtf.format(now));
}
}
Enjoy!
java spring boot scheduled cron
Commentami!