27. Mai 2013

PlayFramework 2.1 use Global in the complete application

27. Mai 2013 - Geschrieben von Martin - Keine Kommentare

While building the new Resigame game server I noticed, that I need a persistent Class for the complete lifetime of my application for storing tasks and other useful things like cached objects (e.g. socket connection to internal communication backend).

So I used the „Global“ class for this purpose. The only steps I had to do was adding the Global.java to a package (otherwise you can’t import it).
Global.java
Afterwards I added a reference to the application.conf:

application.global=core.Global

Now the Global object is accessible in all parts of my application. For example I added a static property called tasks for an object of my TaskScheduler, which is instantiated on application startup.

public class Global extends GlobalSettings {
    public static TaskScheduler tasks;
    public void onStart(Application app) {
        // start task scheduler
        Global.tasks = new TaskScheduler();
        Global.tasks.add(new UserSessionEndExpired());
        Global.tasks.start();
    }
}

this TaskScheduler is now controllable by my REST API:

public static Result stop(Integer taskId) {
    JsonResult result = new JsonResult();
    if(Global.tasks.stop(taskId))
        result.status = 200;
    else
        result.status = 400;
    return result.send();
}

Schreibe einen Kommentar