Akashic Records

Spring Batch에서 REST API로 Quartz Scheduler 변경하기 본문

Spring.io

Spring Batch에서 REST API로 Quartz Scheduler 변경하기

Andrew's Akashic Records 2023. 4. 4. 22:19
728x90

Quartz 스케줄러를 사용하여 Spring Batch Job의 스케줄을 변경하려면, 컨트롤러를 작성하여 새로운 스케줄을 반영할 수 있는 엔드포인트를 생성해야 합니다.

컨트롤러 생성:

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;

@RestController
public class QuartzController {
	 @Autowired
	    private Scheduler scheduler;

	    @PutMapping("/quartz/cron/{jobName}")
	    public String updateCronExpression(@Valid @PathVariable("jobName") String jobName,
	                                 @Valid @RequestBody String cronExpression) {
	        try {
	            JobKey jobKey = new JobKey(jobName);
	            TriggerKey triggerKey = new TriggerKey(jobName + "Trigger");

	            if (scheduler.checkExists(jobKey)) {
	                CronTrigger newTrigger = TriggerBuilder.newTrigger()
	                        .withIdentity(triggerKey)
	                        .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
	                        .build();

	                scheduler.rescheduleJob(triggerKey, newTrigger);
	                return "Schedule updated successfully!";
	            } else {
	                return "Job not found!";
	            }
	        } catch (SchedulerException e) {
	            return "Error occurred while updating schedule: " + e.getMessage();
	        }
	    }
	    
	    @PutMapping("/quartz/interval/{jobName}")
	    public String updateIntervalInSeconds(@Valid @PathVariable("jobName") String jobName,
	                                 @Valid @RequestBody int intervalSeconds ) {
	        try {
	            JobKey jobKey = new JobKey(jobName);
	            TriggerKey triggerKey = new TriggerKey(jobName + "Trigger");

	            if (scheduler.checkExists(jobKey)) {
	                Trigger newTrigger = TriggerBuilder.newTrigger()
	                        .withIdentity(triggerKey)
	                        .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(intervalSeconds).repeatForever())
	                        .build();

	                scheduler.rescheduleJob(triggerKey, newTrigger);
	                return "Schedule updated successfully!";
	            } else {
	                return "Job not found!";
	            }
	        } catch (SchedulerException e) {
	            return "Error occurred while updating schedule: " + e.getMessage();
	        }
	    }
	}


이제 REST API를 사용하여 스케줄을 업데이트할 수 있습니다. 예를 들어, 다음과 같이 curl 명령어를 사용하여 해당 엔드포인트를 호출할 수 있습니다.

curl --location --request PUT 'http://localhost:8080/quartz/interval/batchQuartzJob' \
--header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTY4MDU5NTA0MywiZXhwIjoxNjgwNTk4NjQzfQ.M91f3cFZQp9tBEZoOlJoJMtJpHa2c-KtZaRN5x-enluYzM9FoWl6RIxqYOuMDpja31IwTfNJM3EX1EtsLd7oZw' \
--header 'Content-Type: application/json' \
--data '10'

 

이 예제에서는 jobName 으로 지정된 Job을 찾고, 해당 Job의 트리거 스케줄을 새로운 cronExpression으로 업데이트합니다.

위의 예제를 사용하여 REST API를 통해 Quartz 스케줄을 변경할 수 있습니다. 당연히 컨트롤러 내부의 로직을 변경하여 다양한 작업 및 구성을 수행할 수 있습니다.

728x90
Comments