Calling Remote REST APIs From within the Quartz Scheduler's Jobs

Sometimes, you may need to call REST APIs from within your Scheduler application to accomplish tasks. In this tutorial, we will demonstrate how to invoke a remote REST API from within a Quartz scheduler's job.

If you're interested in learning how to integrate Quartz Scheduler in Spring Boot, we recommend checking out this example.

Here's a sample code for calling remote REST APIs from within the Quartz scheduler's job:

package com.example.payment.job;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class ExampleJob implements Job {

    private static final String TARGET_API = "";
    private RestTemplate restTemplate = new RestTemplate();

    public void execute(JobExecutionContext context) throws JobExecutionException {

        //get data from job detail
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        String paymentId = dataMap.getString("paymentId");

        System.out.println("Executing job for paymentId = " + paymentId);

        HttpHeaders headers = new HttpHeaders();

        ExampleRequest exampleRequest = new ExampleRequest();

        HttpEntity<ExampleRequest> httpExampleRequest =
                new HttpEntity<>(exampleRequest, headers);

        ExampleResponse exampleResponse = restTemplate.postForObject(TARGET_API,
                httpExampleRequest, ExampleResponse.class);

        System.out.println("Payment response =" + exampleResponse.getStatus());

        // if success delete and unschedule job
        try {
            context.getScheduler().deleteJob(new JobKey(paymentId));
            TriggerKey triggerKey = new TriggerKey(paymentId);

        } catch (SchedulerException e) {
            System.out.println("Payment failed =" + paymentId);