Scheduling Tasks in Spring Boot

This application prints out the current time in every 2 seconds.

Directory Structure

Scheduling.java

package com.example.demo;

import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduling {

	// fixedRate is used run the job method in every N milliseconds  
	@Scheduled(fixedRate = 2000) // repeat methods after 2 Seconds
	public void reportCurrentTime() {
		System.out.println((new Date()));
	}
}

Main Application file (ExamApplication.java)

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling // Enabling scheduling for application
public class ExamApplication {

	public static void main(String[] args) {
		SpringApplication.run(ExamApplication.class);		
	}
}

Output

Leave a Reply

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