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 complete tasks, so in this tutorial, we will show you how to call a remote REST API from within a Quartz scheduler's job.

If you are looking for a sample scheduler application then we recommend you to see this example.

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

package com.example.quartz.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);