How to Start and Stop Scheduler in Spring Boot

Spring boot schedulers are used to specify a specific job to run at a specific time. The scheduler will begin when the application does. The job will be executed in accordance with the scheduling configuration. When the spring boot application is stopped, the scheduler will come to a halt. The schedulers are intended to run throughout the lifespan of the application. The schedulers do not start or stop.

In the real world, it is necessary to stop and restart the scheduler without restarting the spring boot application. The ScheduledAnnotationBeanPostProcessor class allows you to programmatically start and stop the scheduler without having to restart the spring boot application. This post will show you how to start and stop a spring boot scheduler programmatically without having to restart the spring boot application.



Scheduler Configuration

The SchedulerConfiguration class contains scheduler configurations. The scheduler configuration class is specified using the @EnableScheduling annotation. The scheduler configuration is used to build a method that will execute on a regular basis. To indicate to schedulers, the method is annotated with @Scheduled.

SchedulerConfiguration.java

package com.yawintutor;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class SchedulerConfiguration {

	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

	@Scheduled(fixedRate = 5000)
	public void scheduleByFixedRate() throws Exception {
		System.out.println("Scheduler is executing "+ format.format(Calendar.getInstance().getTime())+"\n");
	}
}


Scheduler Controller

The scheduler controller class has rest api configuration for starting and stopping the scheduler calls. The scheduler will be started and stopped using the rest api. Another rest api will provide a list of all the schedulers that are presently running in the spring boot application.

SchedulerController.java

package com.yawintutor;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;

@RestController
@RequestMapping("/scheduler")
public class SchedulerController {
	private static final String SCHEDULED_TASKS = "scheduledTasks";

	@Autowired
	private ScheduledAnnotationBeanPostProcessor postProcessor;

	@Autowired
	private SchedulerConfiguration schedulerConfiguration;

	@GetMapping(value = "/stop")
	public String stopSchedule() {
		postProcessor.postProcessBeforeDestruction(schedulerConfiguration, SCHEDULED_TASKS);
		return "OK";
	}

	@GetMapping(value = "/start")
	public String startSchedule() {
		postProcessor.postProcessAfterInitialization(schedulerConfiguration, SCHEDULED_TASKS);
		return "OK";
	}

	@GetMapping(value = "/list")
	public String listSchedules() throws JsonProcessingException {
		Set<ScheduledTask> setTasks = postProcessor.getScheduledTasks();
		if (!setTasks.isEmpty()) {
			return setTasks.toString();
		} else {
			return "Currently no scheduler tasks are running";
		}
	}
}


Spring boot Main class

The spring boot main class is as shown below. There is no change in the spring boot main class.

SpringBootSchedulerApplication.java

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootSchedulerApplication {

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


Pom.xml file

The pom.xml file contains the dependency for spring boot web application starter. The pom.xml file is as shown below.

<?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.5.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>SpringBootScheduler</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootScheduler</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

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

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

</project>


How to stop Scheduler in Spring Boot

If you invoke the below url in the browser, the stop rest api call will be invoked. The rest api call with destroy the scheduler configured to execute. The scheduler will stop running.

http://localhost:8080/scheduer/stop


How to start Scheduler in Spring Boot

If you invoke the below url in the browser, the start rest api call will be invoked. The rest api call with initialise the scheduler configured to execute. The scheduler will start running.

http://localhost:8080/scheduer/start


How to List Scheduler in Sprint Boot

If you invoke the below url in the browser, the list restfully api call will be invoked. The rest api call will list all the schedulers currently running.

http://localhost:8080/scheduer/list

Output

[com.yawintutor.SchedulerConfiguration.scheduleByFixedRate]



Leave a Reply