Playframework 2.0 Play Framework 2.0在服务器启动时安排Akka参与者

Playframework 2.0 Play Framework 2.0在服务器启动时安排Akka参与者,playframework-2.0,akka,Playframework 2.0,Akka,我有一个Akka演员,它验证随机数据,并根据数据的显示时间对其进行一些更改,然后对其进行更新。目前,我正在控制器中使用以下代码: static ActorRef instance = Akka.system().actorOf(new Props(ValidateAndChangeIt.class)); static { Akka.system().scheduler().schedule( Duration.Zero(), Duration.create

我有一个Akka演员,它验证随机数据,并根据数据的显示时间对其进行一些更改,然后对其进行更新。目前,我正在控制器中使用以下代码:

static ActorRef instance = Akka.system().actorOf(new Props(ValidateAndChangeIt.class));
static {
    Akka.system().scheduler().schedule(
        Duration.Zero(),
        Duration.create(5, TimeUnit.MINUTES),
        instance, "VALIDATE"
    );
}
在控制器中使用此选项的问题在于,必须有人访问该控制器处理的页面,参与者才能启动,如果不这样做,则所有内容都会暂停


有没有办法在服务器启动时执行此操作?实际上,我不知道如果参与者生成异常,它会如何表现。它是停止未来的日程安排还是继续?如果没有,是否有任何方法可以让参与者在发生崩溃或错误时重新安排时间?

要在服务器启动时运行代码,请查看:将代码从控制器移动到
onStart()
方法:

public class Global extends GlobalSettings {

  @Override
  public void onStart(Application app) {
    ActorRef instance = Akka.system().actorOf(new Props(ValidateAndChangeIt.class));
    Akka.system().scheduler().schedule(
        Duration.Zero(),
        Duration.create(5, TimeUnit.MINUTES),
        instance, "VALIDATE"
    );
  }  

}

Play Framework提供了一种方式,通过这种方式,可以在
Global.java
中完成作业调度,而无需显式调用它

public class Global extends GlobalSettings {

    private Cancellable scheduler;

    @Override
    public void onStart(Application app) {
        super.onStart(app);
        schedule();
    }

    @Override
    public void onStop(Application app) {
    //Stop the scheduler
        if (scheduler != null) {
            scheduler.cancel();
            this.scheduler = null;
        }
    }
    private void schedule() {
        try {
            ActorRef helloActor = Akka.system().actorOf(new Props(HelloActor.class));
            scheduler = Akka.system().scheduler().schedule(
                    Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds
                    Duration.create(30, TimeUnit.MINUTES),     //Frequency 30 minutes
                    helloActor,
                    "tick",
                    Akka.system().dispatcher(), null);
        }catch (IllegalStateException e){
            Logger.error("Error caused by reloading application", e);
        }catch (Exception e) {
            Logger.error("", e);
        }
    }
}
并创建Actor,
HelloActor.java
在on
onReceive
方法中,您可以处理数据、发送电子邮件等

public class HelloActor extends UntypedActor {

    @Override
    public void onReceive(Object message) throws Exception {
        // Do the processing here. Or better call another class that does the processing.
        // This method will be called when ever the job runs.
        if (message.equals("tick")) {
            //Do something
            // controllers.Application.sendEmails();
        } else {
            unhandled(message);
        }
    }
}
希望这有帮助