带进度条的长时间运行过程示例PlayFramework 2
问题描述:
我想实现用户访问页面时产生的长时间运行的后台进程。我想在这个例子中显示任务的进度:http://web.archive.org/web/20130122091205/http://www.lunatech-research.com/archives/2011/10/31/progressbar-jqueryui-websockets-playframework带进度条的长时间运行过程示例PlayFramework 2
有没有人知道PlayFramework 2.0(使用内置AKKA)的教程?这是为1.2
答
在阅读所有Akka文档的Java http://doc.akka.io/docs/akka/2.0.1/intro/getting-started-first-java.html我想出了这似乎工作得很好。
该系统首先创建一个独特的Actor来处理“报告”(当生成页面被加载时)。该演员产生一个将其进展报告给父母的小孩演员。然后通过JavaScript针对子线程的状态轮询父角色。
一旦孩子结束,它会被终止,一旦家长检测到孩子完成,它就会自行终止。
下面是所有的代码,如果我错过了这个错误的话,请随时将我撕开! (是OK保存状态演员?!?)
控制器代码:
大师演员:
public class MyGeneratorMaster extends UntypedActor {
private int completed = 0;
@Override
public void postStop() {
super.postStop();
System.out.println("Master Killed");
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof actors.messages.ConfigMessage) {
ConfigMessage config = (ConfigMessage) message;
System.out.println("Received Config:" + config.getConfig());
//Need to spawn child actor here..
ActorRef child = this.getContext().actorOf(new Props(MyGeneratorChildWorker.class));
//make the child thread do stuff
child.tell(new ConfigMessage("doSomething!"));
child.tell(akka.actor.PoisonPill.getInstance());//kill the child after the work is complete...
} else if (message instanceof StatusUpdate) {
System.out.println("Got Status Update");
completed = ((StatusUpdate) message).getProgress();
} else if (message instanceof StatusMessage) {
System.out.println("Got Status Message");
getSender().tell(new ResultMessage("Status: " + completed + "%"), getSelf());
if(completed == 100)
{
//kill this actor, we're done!
//could also call stop...
this.getSelf().tell(akka.actor.PoisonPill.getInstance());
}
} else {
System.out.println("unhandled message"+message.toString());
unhandled(message);
}
}
}
的儿童演员:
public class MyGeneratorChildWorker extends UntypedActor {
@Override
public void postStop() {
super.postStop();
System.out.println("Child Killed");
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof ConfigMessage) {
System.out.println("Created Child Worker");
System.out.println("Doing Work:");
try {
for (int i = 0; i <= 100; i++) {
//update parent
this.context().parent().tell(new StatusUpdate(i));
long j = 1;
//waste loads of cpu cycles
while (j < 1E8) {
j = j + 1;
}
}
} catch (Exception ex) {
}
System.out.println("Done Work:");
} else
unhandled(message);
}
}
带有长查询JavaScript的查看页面:
@(message: String)(title: String)(id: String)@main(title) {
<h2>@message</h2>
<script type="text/javascript">
function getPercentage()
{
$.ajax({
type: "GET",
url: "/status/@id",
dataType: "html",
success: function(html)
{
$('#status').html(html);
}
});
}
$(document).ready(function() {
setInterval("getPercentage()",100);
});
</script>
<div id="status">
</div>
}
看起来不错,我会试试看。玩很棒,但是这样的东西只有很少的代码样本。 – Steve 2012-08-12 16:43:23
我知道,它非常令人沮丧! – 2012-08-13 08:37:46
“在演员中存储状态可以吗?!?”演员是少数可以存储状态的地方之一。 – EECOLOR 2013-04-02 12:37:18