com.pubnub.api.managers.ReconnectionManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pubnub Show documentation
Show all versions of pubnub Show documentation
PubNub is a cross-platform client-to-client (1:1 and 1:many) push service in the cloud, capable of
broadcasting real-time messages to millions of web and mobile clients simultaneously, in less than a quarter
second!
package com.pubnub.api.managers;
import com.pubnub.api.PubNub;
import com.pubnub.api.callbacks.PNCallback;
import com.pubnub.api.callbacks.ReconnectionCallback;
import com.pubnub.api.enums.PNReconnectionPolicy;
import com.pubnub.api.models.consumer.PNStatus;
import com.pubnub.api.models.consumer.PNTimeResult;
import lombok.extern.slf4j.Slf4j;
import java.util.Timer;
import java.util.TimerTask;
@Slf4j
public class ReconnectionManager {
private static final int INTERVAL = 3000;
private ReconnectionCallback callback;
private PubNub pubnub;
/**
* Timer for heartbeat operations.
*/
private Timer timer;
public ReconnectionManager(PubNub pubnubInstance) {
this.pubnub = pubnubInstance;
}
public ReconnectionManager setReconnectionListener(ReconnectionCallback reconnectionCallback) {
this.callback = reconnectionCallback;
return this;
}
public void startPolling() {
if (this.pubnub.getConfiguration().getReconnectionPolicy() == PNReconnectionPolicy.NONE) {
log.warn("reconnection policy is disabled, please handle reconnection manually.");
return;
}
registerHeartbeatTimer();
}
private void registerHeartbeatTimer() {
// make sure only one timer is running at a time.
stopHeartbeatTimer();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
callTime();
}
}, 0, INTERVAL);
}
private void stopHeartbeatTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
private void callTime() {
pubnub.time().async(new PNCallback() {
@Override
public void onResponse(PNTimeResult result, PNStatus status) {
if (!status.isError()) {
stopHeartbeatTimer();
callback.onReconnection();
}
}
});
}
}