Spring > Tasks

Guides

Enable scheduling

Application.java
// ...
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);
    }
}

@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.

Create a task

ScheduledTasks.java
// ...
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class ScheduledTasks {
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}

@Scheduled

What Effect
@Scheduled(fixedRate = 5000)
5 seconds after the beginning of the previous execution
@Scheduled(fixedDelay = 5000)
5 seconds after the end of the previous execution
@Scheduled(cron = "...")
Cron expression
Print/export