ApplicationTimer.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package services;
  2. import java.time.Clock;
  3. import java.time.Instant;
  4. import java.util.concurrent.CompletableFuture;
  5. import javax.inject.*;
  6. import play.Logger;
  7. import play.inject.ApplicationLifecycle;
  8. /**
  9. * This class demonstrates how to run code when the
  10. * application starts and stops. It starts a timer when the
  11. * application starts. When the application stops it prints out how
  12. * long the application was running for.
  13. *
  14. * This class is registered for Guice dependency injection in the
  15. * {@link Module} class. We want the class to start when the application
  16. * starts, so it is registered as an "eager singleton". See the code
  17. * in the {@link Module} class to see how this happens.
  18. *
  19. * This class needs to run code when the server stops. It uses the
  20. * application's {@link ApplicationLifecycle} to register a stop hook.
  21. */
  22. @Singleton
  23. public class ApplicationTimer {
  24. private final Clock clock;
  25. private final ApplicationLifecycle appLifecycle;
  26. private final Instant start;
  27. @Inject
  28. public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) {
  29. this.clock = clock;
  30. this.appLifecycle = appLifecycle;
  31. // This code is called when the application starts.
  32. start = clock.instant();
  33. Logger.info("ApplicationTimer demo: Starting application at " + start);
  34. // When the application starts, register a stop hook with the
  35. // ApplicationLifecycle object. The code inside the stop hook will
  36. // be run when the application stops.
  37. appLifecycle.addStopHook(() -> {
  38. Instant stop = clock.instant();
  39. Long runningTime = stop.getEpochSecond() - start.getEpochSecond();
  40. Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s.");
  41. return CompletableFuture.completedFuture(null);
  42. });
  43. }
  44. }