Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing GlobalSettings.onStart and onStop

I'm trying to migrate my GlobalSettings to playframework 2.4 but I'm having a hard time understanding what I'm supposed to do.

Currently my Global is like below, I already moved out the onRequest to the RequestHandler properly:

public class Global extends GlobalSettings {

        private BackgroundTasks backgroundTasks;



        @Override
        public void onStart(Application arg0) {
            Logger.info("Starting background tasks");
            backgroundTasks = new BackgroundTasks();
        }

        @Override
        public void onStop(Application arg0) {
            Logger.info("Stopping background tasks");
            backgroundTasks.shutdown();
            super.onStop(arg0);

            Logger.info("Saving modules data");
            for(Module m: controllers.Application.modules){
                m.saveData();
            }
        }
    }
like image 955
Gonzague Avatar asked Jun 05 '15 13:06

Gonzague


2 Answers

I think it should be along the line of (without package & imports)...

OnStartModule.java:

public class OnStartModule extends AbstractModule {
  @Override
  protected void configure() {    
    bind(BackgroundTasks.class).asEagerSingleton();
  }
}

BackgroundTasks.java:

@Singleton
public class BackgroundTasks {

  @Inject
  public BackgroundTasks(ApplicationLifecycle lifecycle) {
    lifecycle.addStopHook(() -> {
      Logger.info("Stopping background tasks");
      this.shutdown();

      Logger.info("Saving modules data");
      for(Module m: controllers.Application.modules){
        m.saveData();
      }
      return F.Promise.pure(null);
    });
  }
}

application.conf:

play.modules.enabled += "OnStartModule"
like image 61
ePak Avatar answered Nov 02 '22 00:11

ePak


Just as an addendum to the answer. If you instantiate a class using the 'asEagerSingleton()' and it depends the play application to have been already started then you must '@Inject()' the application into your class constructor to ensure it is available.

My issue was due to my old code (pre 2.4) using the static 'import play.api.Play.current' instead of passing the play application object as a constructor argument.

I discovered the answer in the this forum post [Play 2.4] Initialise code after Application has started

like image 22
glidester Avatar answered Nov 02 '22 02:11

glidester