When to Use Google App Engine Task Queue?
You should use task queue when you try to do something taking time such as storing or updating bunch of data to datastore.
In Google App Engine, a http request which isn't returned by timeout should be simply failed. The timeout configured on Google App Engine is 60 seconds.
Please see https://developers.google.com/appengine/articles/deadlineexceedederrors.
So in order to response back to the client quickly, you should use Task Queue for tasks which takes long time.
Push Tasks to Task Queue
I have read an official document of Task Queue and tried to use it.
What frustrates me is the document only explains how to create a task with parameters, push the task to the task queue and pass to the worker servlet. i.e. actual heavy part is treated in the worker servlet.
Of course it is fine, but I felt it was a bit indirect way to push tasks to queue.
What I desired to do is creating task object and pushing it to the queue in one single servlet action.
DeferredTask
Fortunately I quickly found the solution - using DeferredTask.
I will show you the DeferredTask example code. I think showing code is the fastest way to understand how to use DeferredTask ;)
In controller or HttpServlet class, you should write the following code:
byte[] bytes = new byte[1024]; // this line is dummy line. in my actual application, byte array contains data user uploads. Queue queue = QueueFactory.getDefaultQueue(); queue.add(TaskOptions.Builder.withPayload(new MyTask(bytes)));And define a task which should be executed later:
public class MyTask implements DeferredTask { private final byte[] bytes; public MyTask(byte[] bytes) { this.bytes = bytes; } @Override public void run() { // do some nice stuffs! } }After I tried to create a task which implements DeferredTask interface and did some tests, I found some limitations and pitfalls.
- Task size limitation: The (serialized) task object should be less than 100k byte. Is is easy to exceeds limit if a task holds file data which is uploaded by user.
- Serializable: Task class you create should be Serializable. You should add transient to the field definition in the task or implements Serializable interface on classes used in fields in the task.
To avoid serialization issues, I suggests that you should simplify a task implementation as much as you can ;)
Please read the official Google App Engine document.
コメント