DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Implementing Budget Policies and Budget Limits on Databricks
  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]

Trending

  • Designing API-First EMR Architectures in .NET: Enabling Modular Growth in Compliance-Driven Systems
  • S3 Vectors: How to Build a RAG Without a Vector Database
  • LLM Agents and Getting Started with Them
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Adding a RESTful API for the Quartz Scheduler

Adding a RESTful API for the Quartz Scheduler

Learn more about how you can add a RESTful API for the Quartz Scheduler.

By 
John Vester user avatar
John Vester
DZone Core CORE ·
Jul. 16, 19 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
104.2K Views

Join the DZone community and get the full member experience.

Join For Free

As 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 API

  •  QuartzJobDetail — provides details for a given Quartz job

  •  QuartzTigger — provides consolidated information about any triggers in use

  •  QuartzResponse — 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:

  • Specifications to the Rescue

  • Testing Those Specifications

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!

API Quartz (scheduler) job scheduling REST Web Protocols career

Opinions expressed by DZone contributors are their own.

Related

  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Implementing Budget Policies and Budget Limits on Databricks
  • Update User Details in API Test Client Using REST Assured [Video]
  • Create User API Test Client With REST Assured [Video]

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook