Spring Boot Task Scheduler Example
Video
This tutorial is explained in the below Youtube Video.Lets Begin-
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javainuse</groupId> <artifactId>springboot-task-scheduler</artifactId> <version>0.0.1</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.0.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
package com.javainuse.taskconfig; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat( "MM/dd/yyyy HH:mm:ss"); @Scheduled(fixedRate = 10000) public void performTask() { System.out.println("Regular task performed at " + dateFormat.format(new Date())); } @Scheduled(initialDelay = 1000, fixedRate = 10000) public void performDelayedTask() { System.out.println("Delayed Regular task performed at " + dateFormat.format(new Date())); } @Scheduled(cron = "*/5 * * * * *") public void performTaskUsingCron() { System.out.println("Regular task performed using Cron at " + dateFormat.format(new Date())); } }