Created
June 30, 2017 10:54
-
-
Save palmerabollo/05f6d7ad5a8f43c6039ca195abddfd0b to your computer and use it in GitHub Desktop.
SignalHandler to gracefully shutdown a Play 2.5 app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor.ActorSystem; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import play.api.inject.DefaultApplicationLifecycle; | |
import scala.concurrent.duration.Duration; | |
import scala.concurrent.duration.FiniteDuration; | |
import sun.misc.Signal; | |
import javax.inject.Inject; | |
import javax.inject.Singleton; | |
import java.util.concurrent.TimeUnit; | |
@Singleton | |
public class SignalHandler { | |
private static final Logger LOG = LoggerFactory.getLogger(SignalHandler.class); | |
// Docker will kill the container in 10s by default. Give some time to log things before exiting. | |
private static final FiniteDuration STOP_DELAY = Duration.create(9500, TimeUnit.MILLISECONDS); | |
@Inject | |
SignalHandler(ActorSystem actorSystem, DefaultApplicationLifecycle lifecycle) { | |
LOG.info("Add signal handler hooks to the application"); | |
Signal.handle(new Signal("TERM"), signal -> { | |
LOG.info("Shutdown hook: signal {} ({})", signal.getName(), signal.getNumber()); | |
onApplicationStop(actorSystem, lifecycle); | |
}); | |
} | |
private void onApplicationStop(ActorSystem actorSystem, DefaultApplicationLifecycle lifecycle) { | |
LOG.info("Termination required. Swallowing signal to allow current requests to finish"); | |
actorSystem.scheduler().scheduleOnce(STOP_DELAY, lifecycle::stop, actorSystem.dispatcher()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment