GWT, Google App Engine, TimerTask or Thread in a ServiceImpl throw exception

I use GWT and Google App Engine. I have an array of records and I want to update them every 30 minutes. In ServiceImpl, I have the code:

new Timer().schedule(new TimerTask(){ @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } result = updateFeeds(); } }, 30000,Long.MAX_VALUE); 

When I launch the application and when I receive:

 com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List org.joke.planet.client.FeedService.loadFeeds()' threw an unexpected exception: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup) 

in the first line or embedded code.

My question is: HOW can I make a background worker who works in the GWT + AppEngine service?

+7
java multithreading google-app-engine gwt
source share
5 answers

You cannot use java.util.Timer because it creates a regular stream that is not allowed in AppEngine. However, you can use the AppEngine Modules API API as described here: https://developers.google.com/appengine/docs/java/modules/#Java_Background_threads

Please note that you can only use background threads for manually scaled instances. In this example, the background thread issues a message every 30 seconds, forever:

 Thread thread = ThreadManager.createBackgroundThread(new Runnable() { public void run() { try { while (true) { System.err.println("Doing something!"); Thread.sleep(30_000); } } catch (InterruptedException ex) { } } }); thread.start(); 
+3
source share

you can't - the background worker implies a thread, and creating threads in gae doesn't work.

The answer to your task is not to create a stream or background worker, but to use http://code.google.com/appengine/docs/java/config/cron.html

+6
source share

You, sir, can benefit from adding a new ThreadManager class.

https://developers.google.com/appengine/docs/java/backends/overview#background_threads

Use ThreadManager.currentRequestThreadFactory () to get a Thread factory that will interrupt spawned threads as soon as the current request is complete, and ThreadManager.backgroundThreadFactory () to spawn threads that will last as long as you want (but only works on backends)

For frontend requests, it is recommended to keep track of your threads and call thread.join () if you want them to finish before the appengine request filter interrupts them.

+3
source share

See also task queues as an alternative.

0
source share

The problem is not only in the application, but in any Servlet container. When someone is in the service method (which you are always in the Servlet container), you cannot create threads and hibernate.

In today's scalable world, thread.sleep services are a bad thing ....

-one
source share

All Articles