用Appengine进行多线程 [英] Multithreading with Appengine
问题描述
由于Appengine不允许java多线程,那么我们如何才能将现有的多线程代码迁移到平台?
例如我有以下代码:
线程t =新线程(){
public boolean alive = true;
public void run(){
while(alive){
try {
Thread.sleep(5000);
getNewNotifications();
} catch(InterruptedException e){
//什么也不做
} catch(IOException e){
}
}
}
} ;
t.start()
函数getNewNotification()会执行一些Rest / HTTP调用,这可能包括可能无限期返回的其他一些流程。我已阅读任务队列
是解决方案,但我们如何将此简单代码转换为App引擎友好代码?
上面的代码如何使用Task队列实现?例如每5秒钟调用 getNewNotifications()
。
这个函数会从服务器得到一些结果,解析结果,然后根据结果执行需要执行的活动/工作。根据您的预算(查看后端帐单),您也可以通过使用 //developers.google.com/appengine/docs/java/config/cronrel =nofollow>计划任务。
您可以指定任务在 cron.xml
文件中:
<?xml version =1.0encoding =UTF-8?>
< cronentries>
< cron>
< url> / getNewNotifications< / url>
< description>每5分钟收到一次新通知< / description>
< schedule>每5分钟< / schedule>
< / cron>
< / cronentries>
当然,您需要有一个servlet(或者您使用的任何框架)映射到URL / getNewNotifications
。
您还应该确保网址是安全的(通常您不希望用户致电该网址)。
Since Appengine won't allow java multithreading, how then can we migrate our existing multithreaded code to the platform?
For example I have the following code:
Thread t = new Thread() {
public boolean alive = true;
public void run() {
while (alive) {
try {
Thread.sleep(5000);
getNewNotifications();
} catch (InterruptedException e) {
// Do nothing
} catch (IOException e) {
}
}
}
};
t.start()
The function getNewNotification() does some several Rest/HTTP calls, that may include some other process that may return indefinitely. I have read the Task Queue
is the solution, however how do we convert this simple code into App engine-friendly code?
How is the code above implemented using Task queue? For example to call getNewNotifications()
for every five seconds.
And that function will get some results from the server, parse the result and then execute the activities/work it needs to do based on the result.
Depending on your budget (check billing for backends), you can achieve this also by using Scheduled Tasks.
You would specify the task in the cron.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/getNewNotifications</url>
<description>Get new notifications every 5 minutes</description>
<schedule>every 5 minutes</schedule>
</cron>
</cronentries>
Of course, you need to have a servlet (or whatever framework you are using) mapped to the URL /getNewNotifications
.
You should also make sure, that the URL is secure (normally you don't want your users call that URL).
这篇关于用Appengine进行多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!