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
在ononReceive
方法中,可以做数据的处理,发送邮件等。
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);
}
}
}
希望这可以帮助。