Getting Started with spring boot scheduler `@Scheduled`.

Getting Started with spring boot scheduler `@Scheduled`.

A lot of times we need to run couple CORN or scheduled scripts, if your spring boot developer without having much hassle we can start Spring boot application and create task or run a scheduled jobs, so lets begin with small proof of concept to start Spring Scheduler and running the task with @Scheduled annotation

Step 1 : Create An application with following POM

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.scheduled</groupId>
    <artifactId>poc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>poc</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Step 2 : Enable Auto Configuration

In the Main Application Class Where @SpringBootApplication annotation is present annotate with @EnableScheduling follow the example below

@SpringBootApplication
@EnableScheduling
public class PocApplication {

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

}

Step 3 : Create your service component and implement your business logic.

As i am very lazy to to come with proper example,my service will just print hello world :-p,

@Service
public class HelloworldService {
    
    public void print() {
        System.out.println("hello world");    
    }
}

Step 4 : Implementing Scheduler

@Component
public class MyScheduler {
    @Autowired
    HelloworldService helloworldService;

    @Scheduled(fixedRate = 2000)
    public void performTask() {
        helloworldService.print();
    }
}

Few points to remember while writing scheduler

  • Class should be annotated with @Component
  • The function implementing Scheduler should always be with void return type
  • The function should not have any parameters
  • And remember to annotate your function with @Scheduled

Now i will begin explaining different options supported by @Scheduled annotation.

1. Fixed Rate

The execution will trigger with fixed rate specified.So the example code below will execute every 2 seconds.
```
@Scheduled(fixedRate = 2000)
public void performTask() {
    helloworldService.print();
}
```

2. Fixed Delay

    The Start of the execution will be delayed by specified time, example code is pasted below
    ```
    @Scheduled(fixedDelay = 2000)
public void performDelayedTask() {
    helloworldService.print();
}
    ```

3. Fixed Rate and Initial Delay

The example code will trigger ever two seconds with the initial delay of 2 seconds
```
@Scheduled(initialDelay = 2000,fixedRate = 2000)
public void performDelayedFixedTask() {
    helloworldService.print();
}
```

4. With Corn Expression

The Code is self explanatory the example code will trigger based on corn expression,my expression triggers the code every min.
```
Scheduled(cron = "0 * * * * ?")
public void performCornTask() {
    helloworldService.print();
}
```

Happy Coding... Hello World...!!!  :-P