Shutdown Spring boot Application Job Programatically

Hi Folks,

Recently, one of my colleague approached me for following problem statement:

He develop a spring-boot application which is running as a cron job. The job interval time say every 2 mins. The application pulls the number of records from upstream system and process each record in loop updating 5-6 transaction tables for each record.

Now if in case of newer version of job needs deployment or need arises to stop (shutdown) current spring boot application could cause a dirty read in database tables. (assuming that at time of stopping or killing java process the program might processing the record and updating the intermidiate database tables).

So how gracefully we can shutdown the spring boot application without loosing or corrupting any data ?

To simulate the problem statement, I created a sample spring boot application job as below

So the idea is:

  • create a Sample spring boot cron job.
  • created a Controller and setting the System property by calling API.
  • So its like before proessing each record in loop, read the same property value in sheduler at line 24
  • at line 25, I can write the code to check strPropVal and if its set to “Shutdown” or “STOP” then at line 26 I can say System.exit(0)

In short, scheduler got running then I call the api using curl command or using browser URL to set the System.setProperty value, as soon as API got invoked the property got set and schedular reads the same property to decide to shutdown.

See the controller class below

Note Controller and Spring boot scheduler are part of same project or atleast they should be running in same machine (VM)

See yaa !!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s