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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot
  • Micro-Frontends in a Microservice Architecture
  • Reactive Kafka With Spring Boot
  • Curating Efficient Distributed Application Runtime (Dapr) Workflows

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • AI, ML, and Data Science: Shaping the Future of Automation
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Calling a Client Via Spring @schedule Cron Job

Calling a Client Via Spring @schedule Cron Job

In this article, a cron job will be set up that will run parametrically in a certain period using Spring's scheduling feature.

By 
Erkin Karanlık user avatar
Erkin Karanlık
·
Oct. 22, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.2K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, a cron job will be set up that will run parametrically in a certain period using Spring's scheduling feature. Period information will be adjustable parametrically from the application.properties file.

Overview

In the example, parameter information is given to run every minute.

Properties files
 
schedule.minute.param:1


Parameter information

The schedule method will be run in a minute time period. It will trigger the method we want to call within the service class. This method will call a client jar from integration_microservice via feign client and get the response information.

For this architecture, we will have two microservices on Spring Boot.  The first of these will be job_microservice and the second will be integration_microservice.

The schedule method in job_microservice will be run periodically and the service impl will be called.

The jobIntegrationClientFacades service class will be called from the ServiceImpl class. JobIntegrationFeignClient class will be called from jobIntegrationClientFacades to go to integration_microservice.

Access to integration_microservice will be provided through the @FeignClient annotation within the JobIntegrationFeignClient class.

The response received via the relevant client.jar controller class in integration_microservice will be returned to job_microservice.

Various validations can be made on the response received in job_microservice service_impl.

Logging can be done according to the response. Error situations can be separated and logged according to the incoming response code.  On successful response, the flow will be terminated. If desired, the successful response can be logged, but it may cause the log size to increase.

Enter project name


New Module: job_microservice


New module: integration_microservice


job_microservice file structure


integration_microservice file structure

The following flow should be followed for two microservices: 

1. job_microservice:

  • A new Spring Boot Maven module named job_microservice should be created.
  • spring-cloud-starter-openfeign should be added as a dependency.

spring-cloud-starter-openfeign added as a dependency

2. integration_microservice:

  • A new Spring Boot Maven module named integration_microservice should be created.
  • spring-cloud-starter-web should be added as a dependency.

Add Spring Web as a dependency

Note: Creating a client in integration_microservice and using client features and methods are not covered in this article, as they are the subject of another article. Client creation stages are out of scope in this article. 

job_microservice 

  • In order to run the Spring @schedule feature in the JobApplication.kt class, the @EnableScheduling annotation must be added.
  • In order to communicate between two microservices via feignclient, the @EnableFeignClients annotation must be added.

JobApplication.kt:

Kotlin
 
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.cloud.openfeign.EnableFeignClients
import org.springframework.scheduling.annotation.EnableScheduling

@SpringBootApplication
@EnableFeignClients
@EnableScheduling
class JobmicroserviceApplication

fun main(args: Array<String>) {
    runApplication<JobmicroserviceApplication>(*args)
}


CronScheduler

  • A class named CronScheduler is created with @component annotation.
  • With @Value("\${schedule.minute.param:}"), the "schedule.minute.param" value in the application properties file is read parametrically.
  • It is run on a minute basis with the "schedule.minute.param" value taken from the parametric application properties file with @Scheduled(cron = "* */\${schedule.minute.param} * * * ?").
    •   First *: Seconds of operation
    •   Second *: Minute-based operation
    •   Third *: Clockwise operation
    •   Fourth *: Day of month operation
    •   Fifth *: Month-based operation
    •   Sixth *: Day of the week run

The @schedule annotation is added right above the relevant method.  As can be seen below, the prepareClientCall function is defined as a unit return type to perform the operation without waiting for any response.

By including jobService, prepareClientCall in the jobService interface is called.  

  • CronScheduler.kt:
Kotlin
 
@Component
class CronScheduler(val jobService: JobService) {

    @Value("\${schedule.minute.param:}")

    @Scheduled(cron = "* */\${schedule.minute.param} * * * ?")
    fun prepareClientCall(): Unit {
        jobService.prepareClientCall()
    }
}

JobService.kt

interface JobService {

    fun prepareClientCall(): Unit

}


  • The prepareClientCall method in the JobServiceImpl class is called by the @schedule function.  Inside, the prepareClientCall() method in jobIntegrationClientFacades is called.
  • Client response is set to the response object.
  • ResponseCode in the response is controlled with ResponseControl.
  • The response object here may vary depending on the client you will call. The responseCode here is given as an example.
  • "0" appeared as a success in Responsecontrol and was returned. In the success case, the flow is terminated.
  • It is logged as a "-2" system exception and a "-1" business exception. The else part has been thrown away.
  • The exception is logged in the main function.

Note: The response object here is given through the sample client.

  • JobServiceImpl.kt:
Kotlin
 


@Service
class JobServiceImpl(
    private val jobIntegrationClientFacades: JobIntegrationClientFacades,
) : JobService {


    private val log = logger()


    fun responseControl(response: ResponseEntity<ClientResult>) {

        if (result.body?.resultCode ?: -3 == 0) {
            log.info("resultCode - "  + result.body?.resultCode  +  System.currentTimeMillis() / 1000 )
			return; // success case
        } else if (result.body?.resultCode ?: -3 == -2) {
            log.info("resultCode - "  + result.body?.resultCode  +  System.currentTimeMillis() / 1000 ) // -2 system exception
        } else if (result.body?.resultCode ?: -3 == -1) {
            log.info("resultCode - "  + result.body?.resultCode  +  System.currentTimeMillis() / 1000 ) // -1 business exception
        } else if (result.body?.resultCode ?: -3 == -3) {
            log.info("resultCode - "  + result.body?.resultCode  +  System.currentTimeMillis() / 1000 ) // -3 null pointer exception
        } else {
            throw e
        }

    }

    override
    fun prepareClientCall(): Unit {
        try {
            val response = jobIntegrationClientFacades.prepareClientCall()
            responseControl(response)
        } catch (exp: Exception) {
            log.info("exception - "  + exp + System.currentTimeMillis() / 1000 ) // exception 
        }
    }
   
}


Facades

  • Below, JobIntegrationClient is called from JobIntegrationClientFacades.
  • JobIntegrationFeignClient is called from JobIntegrationClient.
  • A postMapping request was provided to integration_microservice with feignClient to call client.jar in JobIntegrationFeignClient.

  • JobIntegrationClientFacades.kt:
Kotlin
 
@Service
class JobIntegrationClientFacades(val jobIntegrationClient: JobIntegrationClient) {

    fun prepareClientCall(): ResponseEntity<ClientResult> {
        return jobIntegrationClient.prepareClientCall()
    }

}


  • JobIntegrationClient.kt:
Kotlin
 
@Service
class JobIntegrationClient(
    val jobIntegrationFeignClient: JobIntegrationFeignClient
) {

    fun prepareClientCall(): ResponseEntity<ClientResult> {
        return jobIntegrationFeignClient.prepareClientCall()
    }
}


  • JobIntegrationFeignClient.kt:
Kotlin
 
@FeignClient("integration_microservice", url = "http://localhost:10000")
interface JobIntegrationFeignClient {

    @PostMapping("/jobIntegrationClient/prepareClientCall")
    fun prepareClientCall(): ResponseEntity<ClientResult>


}


integration_microservice

Controller

  • The @RequestMapping("/jobIntegrationClient") request that comes with the RestController annotation is checked.
  • The correctness of matching "/prepareClientCall" with @PostMapping("/prepareClientCall") is checked.
  • prepareClientCall() in jobIntegrationClientService is called.
  • The prepareClientCall() function in the JobIntegrationClientServiceImpl is called from the JobIntegrationClientService interface.
  • The prepareClientCall() function is called from the client that you want to call from JobIntegrationClientServiceImpl.

  • JobController.kt:
Kotlin
 
@RestController
@RequestMapping("/jobIntegrationClient")
class JobController(
    val jobIntegrationClientService: jobIntegrationClientService
) {

    @PostMapping("/prepareClientCall")
    fun prepareClientCall(): ResponseEntity<ClientResult> {
        return jobIntegrationClientService.prepareClientCall()
    }

  
}


  • JobIntegrationClientService.kt:
Kotlin
 

interface JobIntegrationClientService {

    fun prepareClientCall(): ResponseEntity<ClientResult>
}


  • JobIntegrationClientServiceImpl.kt:
Kotlin
 
@Service
class JobIntegrationClientServiceImpl(
    private val xClient: XClient
) : JobIntegrationClientService {

    override
    fun prepareClientCall(): ResponseEntity<ClientResult> {
        return xClient.prepareClientCall()
    }

}


  • The Response object is returned to the JobIntegrationFeignClient prepareClientCall() function in job_microservice via the JobController as ResponseEntity<ClientResult>.
  • A response is received in JobServiceImpl in job_microservice.
  • JobIntegrationFeignClient.kt:
Kotlin
 

@FeignClient("integration_microservice", url = "http://localhost:10000")
interface JobIntegrationFeignClient {

    @PostMapping("/jobIntegrationClient/prepareClientCall")
    fun prepareClientCall(): ResponseEntity<ClientResult>


}


Crons Schedule (computer science) Spring Boot microservice

Opinions expressed by DZone contributors are their own.

Related

  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot
  • Micro-Frontends in a Microservice Architecture
  • Reactive Kafka With Spring Boot
  • Curating Efficient Distributed Application Runtime (Dapr) Workflows

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!