Adding a RESTful API for the Quartz Scheduler
Learn more about how you can add a RESTful API for the Quartz Scheduler.
Join the DZone community and get the full member experience.
Join For FreeAs a continuation of my previous article, I thought it would be nice to create a RESTful API into the information being maintained by the Quartz scheduler. This way, a client can make standard REST requests to handle the following functionality:
Retrieve information on the Quartz Scheduler
Retrieve a list of job keys (which are the items which make a given job unique in Quartz)
Retrieve detailed information for a given job key, including any associated triggers
Delete a job that is currently scheduled on the Quartz Scheduler
Creating DTO Models for API Responses
In order to provide a clean result set for the API, I decided to create some DTO classes for the Scheduler API:
QuartzInformation
— will provide high-level summary information for the APIQuartzJobDetail
— provides details for a given Quartz jobQuartzTigger
— provides consolidated information about any triggers in useQuartzResponse
— a simple class to return when a delete request is made to the API
As an example, the QuartzInformation
class is provided below:
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class QuartzInformation {
private String version;
private String schedulerName;
private String instanceId;
private Class threadPoolClass;
private int numberOfThreads;
private Class schedulerClass;
private boolean isClustered;
private Class jobStoreClass;
private long numberOfJobsExecuted;
private Date startTime;
private boolean inStandbyMode;
private List<String> simpleJobDetail;
public String getSchedulerProductName() {
return "Quartz Scheduler (spring-boot-starter-quartz)";
}
}
Creating the Scheduler Service
With the DTO classes in place, the SchedulerService
was created to handle the service-level of the API. Using constructor-based injection, the following set-up was added to the SchedulerService
:
@Slf4j
@Service
public class SchedulerService {
private Scheduler scheduler;
public SchedulerService(Scheduler scheduler) {
this.scheduler = scheduler;
}
}
From there, the getSchedulerInformation()
method was added, to provide high-level information about the Quartz scheduler that is currently running:
public QuartzInformation getSchedulerInformation() throws SchedulerException {
SchedulerMetaData schedulerMetaData = scheduler.getMetaData();
QuartzInformation quartzInformation = new QuartzInformation();
quartzInformation.setVersion(schedulerMetaData.getVersion());
quartzInformation.setSchedulerName(schedulerMetaData.getSchedulerName());
quartzInformation.setInstanceId(schedulerMetaData.getSchedulerInstanceId());
quartzInformation.setThreadPoolClass(schedulerMetaData.getThreadPoolClass());
quartzInformation.setNumberOfThreads(schedulerMetaData.getThreadPoolSize());
quartzInformation.setSchedulerClass(schedulerMetaData.getSchedulerClass());
quartzInformation.setClustered(schedulerMetaData.isJobStoreClustered());
quartzInformation.setJobStoreClass(schedulerMetaData.getJobStoreClass());
quartzInformation.setNumberOfJobsExecuted(schedulerMetaData.getNumberOfJobsExecuted());
quartzInformation.setInStandbyMode(schedulerMetaData.isInStandbyMode());
quartzInformation.setStartTime(schedulerMetaData.getRunningSince());
for (String groupName : scheduler.getJobGroupNames()) {
List<String> simpleJobList = new ArrayList<>();
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
String jobName = jobKey.getName();
String jobGroup = jobKey.getGroup();
List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
Date nextFireTime = triggers.get(0).getNextFireTime();
Date lastFireTime = triggers.get(0).getPreviousFireTime();
simpleJobList.add(String.format("%1s.%2s - next run: %3s (previous run: %4s)", jobGroup, jobName, nextFireTime, lastFireTime));
}
quartzInformation.setSimpleJobDetail(simpleJobList);
}
return quartzInformation;
}
Getting a list of job keys is a very simple request:
public List<JobKey> getJobKeys() throws SchedulerException {
List<JobKey> jobKeys = new ArrayList<>();
for (String group : scheduler.getTriggerGroupNames()) {
jobKeys.addAll(scheduler.getJobKeys(groupEquals(group)));
}
return jobKeys;
}
Populating the job details, with trigger information, was the most complex method and was written below:
public QuartzJobDetail getJobDetail(String name, String group) throws SchedulerException {
JobDetail jobDetail = scheduler.getJobDetail(jobKey(name, group));
QuartzJobDetail quartzJobDetail = new QuartzJobDetail();
BeanUtils.copyProperties(jobDetail, quartzJobDetail);
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey(name, group));
if (CollectionUtils.isNotEmpty(triggers)) {
List<QuartzTrigger> quartzTriggers = new ArrayList<>();
for (Trigger trigger : triggers) {
QuartzTrigger quartzTrigger = new QuartzTrigger();
BeanUtils.copyProperties(trigger, quartzTrigger);
if (trigger instanceof SimpleTrigger) {
SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
quartzTrigger.setTriggerType(simpleTrigger.getClass().getSimpleName());
quartzTrigger.setRepeatInterval(simpleTrigger.getRepeatInterval());
quartzTrigger.setRepeatCount(simpleTrigger.getRepeatCount());
quartzTrigger.setTimesTriggered(simpleTrigger.getTimesTriggered());
} else if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
quartzTrigger.setTriggerType(cronTrigger.getClass().getSimpleName());
quartzTrigger.setTimeZone(cronTrigger.getTimeZone());
quartzTrigger.setCronExpression(cronTrigger.getCronExpression());
quartzTrigger.setExpressionSummary(cronTrigger.getExpressionSummary());
}
quartzTriggers.add(quartzTrigger);
}
quartzJobDetail.setTriggers(quartzTriggers);
}
return quartzJobDetail;
}
Finally, the service method to delete a job was defined as follows:
public QuartzJobDetail getJobDetail(String name, String group) throws SchedulerException {
JobDetail jobDetail = scheduler.getJobDetail(jobKey(name, group));
QuartzJobDetail quartzJobDetail = new QuartzJobDetail();
BeanUtils.copyProperties(jobDetail, quartzJobDetail);
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey(name, group));
if (CollectionUtils.isNotEmpty(triggers)) {
List<QuartzTrigger> quartzTriggers = new ArrayList<>();
for (Trigger trigger : triggers) {
QuartzTrigger quartzTrigger = new QuartzTrigger();
BeanUtils.copyProperties(trigger, quartzTrigger);
if (trigger instanceof SimpleTrigger) {
SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
quartzTrigger.setTriggerType(simpleTrigger.getClass().getSimpleName());
quartzTrigger.setRepeatInterval(simpleTrigger.getRepeatInterval());
quartzTrigger.setRepeatCount(simpleTrigger.getRepeatCount());
quartzTrigger.setTimesTriggered(simpleTrigger.getTimesTriggered());
} else if (trigger instanceof CronTrigger) {
CronTrigger cronTrigger = (CronTrigger) trigger;
quartzTrigger.setTriggerType(cronTrigger.getClass().getSimpleName());
quartzTrigger.setTimeZone(cronTrigger.getTimeZone());
quartzTrigger.setCronExpression(cronTrigger.getCronExpression());
quartzTrigger.setExpressionSummary(cronTrigger.getExpressionSummary());
}
quartzTriggers.add(quartzTrigger);
}
quartzJobDetail.setTriggers(quartzTriggers);
}
return quartzJobDetail;
}
Adding a RESTful Controller Class
With the services in place, the next step is to add the SchedulerController
class. The GET
request for retrieving general information about the Quartz scheduler is also included in the sample below:
@Controller
@CrossOrigin
@RequestMapping(value = "/scheduler/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SchedulerController {
private SchedulerService schedulerService;
public SchedulerController(SchedulerService schedulerService) {
this.schedulerService = schedulerService;
}
@GetMapping(value = "information")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<QuartzInformation> getSchedulerInformation() {
try {
return new ResponseEntity<>(schedulerService.getSchedulerInformation(), HttpStatus.OK);
} catch (SchedulerException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
Since the job keys and job detail methods are very close to the scheduler information method, they are omitted here. However, the design of the DELETE
request is shown below:
@DeleteMapping(value = "deleteJob")
@ResponseStatus(HttpStatus.ACCEPTED)
public ResponseEntity<QuartzResponse> deleteJob(@RequestParam String name, @RequestParam String group) {
try {
return new ResponseEntity<>(schedulerService.deleteJobDetail(name, group), HttpStatus.ACCEPTED);
} catch (SchedulerException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Putting the API to Use
Using a Postman client, the following request can be made to Spring Boot service:
GET http://localhost:9000/scheduler/information
This returns a 200 OK
response with the following payload:
{
"version": "2.3.0",
"schedulerName": "MyInstanceName",
"instanceId": "Instance1",
"threadPoolClass": "org.quartz.simpl.SimpleThreadPool",
"numberOfThreads": 10,
"schedulerClass": "org.quartz.impl.StdScheduler",
"jobStoreClass": "org.springframework.scheduling.quartz.LocalDataSourceJobStore",
"numberOfJobsExecuted": 1,
"startTime": "2019-07-14T20:02:11.766+0000",
"inStandbyMode": false,
"simpleJobDetail": [
"DEFAULT.Member Statistics Job - next run: Sun Jul 14 16:03:11 EDT 2019 (previous run: Sun Jul 14 16:02:11 EDT 2019)",
"DEFAULT.Class Statistics Job - next run: Sun Jul 14 16:05:00 EDT 2019 (previous run: null)"
],
"clustered": false,
"schedulerProductName": "Quartz Scheduler (spring-boot-starter-quartz)"
}
To retrieve a list of job keys, the following request can be made:
GET http://localhost:9000/scheduler/jobKeys
This returns a 200 OK
response with the following payload:
[
{
"name": "Member Statistics Job",
"group": "DEFAULT"
},
{
"name": "Class Statistics Job",
"group": "DEFAULT"
}
]
Using the job key information (listed above), one of the value sets can be used to return the full details for a given Quartz job and trigger:
GET http://localhost:9000/scheduler/jobDetail?name=Member+Statistics+Job&group=DEFAULT
Again, a 200 OK
response is received, with the following payload:
{
"name": "Member Statistics Job",
"group": "DEFAULT",
"description": null,
"jobClass": "com.gitlab.johnjvester.jpaspec.jobs.MemberStatsJob",
"concurrentExectionDisallowed": true,
"persistJobDataAfterExecution": false,
"durable": true,
"requestsRecovery": false,
"triggers": [
{
"name": "Member Statistics Trigger",
"group": "DEFAULT",
"description": null,
"calendarName": null,
"nextFireTime": "2019-07-14T20:48:15.343+0000",
"previousFireTime": "2019-07-14T20:47:15.343+0000",
"startTime": "2019-07-14T20:46:15.343+0000",
"endTime": null,
"finalFireTime": null,
"priority": 0,
"misfireInstruction": 4,
"triggerType": "SimpleTriggerImpl",
"repeatInterval": 60000,
"repeatCount": -1,
"timesTriggered": 2,
"timeZone": null,
"cronExpression": null,
"expressionSummary": null
}
]
}
Finally, if the decision is made to delete a job, a URL similar to what is listed below can be submitted:
DELETE http://localhost:9000/scheduler/deleteJob?name=Member+Statistics+Job&group=DEFAULT
This time, a 202 ACCEPTED
response will be received, with the following information:
{
"type": "DELETE",
"name": "Member Statistics Job",
"group": "DEFAULT",
"result": true,
"status": "DEFAULT.Member Statistics Job has been successfully deleted"
}
Conclusion
This article is the fourth in a series of articles. Below are a list of all of the articles in this series:
If you would like to see the full source code referenced in this article, my repository can be found here.
Have a really great day!
Opinions expressed by DZone contributors are their own.
Comments