Spring Boot Scheduler Job @EnableScheduling | @Schedule Example

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the TaskExecutor and TaskScheduler interfaces, respectively.
In this tutorials, we are going to see how can we use TaskScheduler using Spring Boot Scheduler. And also we will have a discussion on how to use Spring @EnableScheduling and @Scheduled annotations.
To enable scheduling tasks in spring boot applicaiton, we can use the java based @EnableScheduling annotation.
@Configuration
@EnableScheduling
public class SpringBootConfig {
    // config details..
}
If you are in xml based configuration, you can directly use <task:annotation-driven> in you config xml.
The scheduler methods should not return any values, that means it should be void.
The scheduler methods should not accept any parameters.
The @Scheduled annotation is used to create a schedule, it can be added to a method along with the data. Here are the different schedules :
@Scheduled(fixedDelay = 6000)
The duration between the end of the end of last task and start of next task is fixed. The next task always waits until the previous one is finished.
package com.onlinetutorialspoint;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedDelay = 6000)
    public void reportCurrentTime() {
        System.out.println("The time is -: "+ dateFormat.format(new Date()));
    }
}
@Scheduled(fixedRate = 6000)
Fixed Rate makes the task on periodic intervals even if the last invocation may still be running.
@Component
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("The time is -: "+ dateFormat.format(new Date()));
    }
}
@Scheduled(fixedRate = 6000, initialDelay = 1000)
An initial delay can be specified indicating the number of milliseconds to wait before the first execution of the method.
@Component
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate = 6000, initialDelay = 1000)
    public void reportCurrentTime() {
        System.out.println("The time is -: "+ dateFormat.format(new Date()));
    }
}
Some times these schedulers (delays and rates) are not enough to fulfill our requirement, then a cron expression may be provided.
Let’s take an example, I would like to execute a perticular functionality only on weekdays (MON-FRI). We can define this as following..
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
    // do something here..
}
"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight

You can see more details on cron expresions here.
Happy Learning:)

@Component,@Service,@Repository,@Controller in spring
How to enable Swagger in Spring Boot Application
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Kafka Producer Example
Spring Boot Actuator Database Health Check
How to get Current UTC Time in Java
Spring Boot Hazelcast Cache Example
Spring Boot Actuator Example
Simple Spring Boot Example
Spring Boot EhCache Example
Spring Boot Kafka Consume JSON Messages Example
Spring Boot MongoDB + Spring Data Example

@Component,@Service,@Repository,@Controller in spring
How to enable Swagger in Spring Boot Application
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Kafka Producer Example
Spring Boot Actuator Database Health Check
How to get Current UTC Time in Java
Spring Boot Hazelcast Cache Example
Spring Boot Actuator Example
Simple Spring Boot Example
Spring Boot EhCache Example
Spring Boot Kafka Consume JSON Messages Example
Spring Boot MongoDB + Spring Data Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment