spring-bootscheduled-taskscloud-foundryspring-scheduledpcf

PCF solution to restrict a spring @Scheduled job to run only in one instance in cloud environment


I have a spring @Scheduled job in Pivotal Cloud Foundry (PCF) which could run in multiple instances, but I want to restrict it to run only in one instance in PCF cloud environment.

Does PCF provide any out-of-the-box solution for this or do we need to do changes in our code?

Any suggestion will be helpful for me to implement it.


Solution

  • One way to make this work is to look at the INSTANCE_INDEX or CF_INSTANCE_INDEX (they are the same) environment variable. This will have the instance number of your application instance. It's zero based, so it'll be 0 to the number of application instances you have minus one (ex: 5 AI's == 0-4).

    There's a number of ways to make this work in your app, but the high level idea is that you pick an index number and make it so that scheduling only runs on that index number. Zero is what you'd typically pick since there is always a zeroth instance, but you can run it on any index.

    As for ways you could make this happen:

    I'm sure there's other options too. Those are just the ones off the top of my head.