Home > Net >  Notify another hazelcast instance in Spring boot
Notify another hazelcast instance in Spring boot

Time:09-22

I have two instances running for my spring boot project. There I have a scheduled task with defined interval. Now the problem is, both instances are running that scheduled task. I used lock but it just locked when it was working on that task. Once it finishes, another instance starts working on that. Is it possible to run scheduled tasks from one instance only? If one instance completes the task, then no one will work on that in between defined interval?

CodePudding user response:

When you submit a Runnable/Callable you can specify which member it runs on in a couple of ways. scheduleOnKeyOwner() and scheduleOnMember() might be the ones to pick from.

scheduleOnMember() fairly obviously lets you pick which member.

scheduleOnKeyOwner() let's you pick any one member, if you need one but don't care which one. For example, the key owner for integer key 1. One node in the cluster will look after that key (it doesn't need to exist).

CodePudding user response:

Apart from what Neil suggested you will likely face an issue where to submit the task from. From the first instance started? How does it know it's the first one? Etc.

The solution is to use com.hazelcast.scheduledexecutor.NamedTask or com.hazelcast.scheduledexecutor.TaskUtils#named(String, Runnable) helper method:

public class ScheduleSingleTask {

    public static void main(String[] args) {
        new Thread(new MyApp()).start();
        new Thread(new MyApp()).start();
    }

    public static class MyApp implements RunnableEx {
        @Override
        public void runEx() {
            HazelcastInstance hz = Hazelcast.newHazelcastInstance();

            IScheduledExecutorService myScheduler = hz.getScheduledExecutorService("myScheduler");
            try {
                IScheduledFuture<Object> future = myScheduler.scheduleAtFixedRate(
                        TaskUtils.named(
                                "myTask",
                                (RunnableEx) () -> System.out.println(System.currentTimeMillis()   " Hello World!")
                        ),
                        0, 5, SECONDS);
            } catch (DuplicateTaskException e) {
                // expected on one of the members
            }

        }
    }
}
  • Related