How to create startup tasks¶
Problem¶
You want to have some code executed within the clustered service after start.
Discussion¶
The onStart
method on the ClusteredService
is useful to initialize objects and rehydrate state from a snapshot, but you cannot safely run logic that needs to be deterministic in your cluster at this time.
If you try to use either ClusteredService.offer
or ClusteredService.scheduleTimer
in onStart
, you will receive an exception with the message ERROR - sending messages or scheduling timers is not allowed from onStart
.
A better approach to do this deterministically is to react to the first client session being connected and then schedule a timer or send in a message via the cluster offer, for example:
public class YourClusteredService implements ClusteredService
{
private Cluster cluster;
private boolean firstClient = true;
...
@Override
public void onStart(Cluster cluster, Image snapshotImage)
{
this.cluster = cluster;
...
}
@Override
public void onSessionOpen(ClientSession session, long timestamp)
{
log.info("Cluster Client Session opened");
if (firstClient) {
//sequence a message via cluster.scheduleTimer(...) or cluster.offer(...)
firstClient = false;
}
}
...
}