Home‎ > ‎Server‎ > ‎App Engine‎ > ‎

Task


Below are 2 ways I like to do tasks on App Engine.
A. Start as a deferred task with out a servlet.
B. Start a task using a servlet.  

A. Start a DeferredTask

I like this method the best because it's much simpler to start a task. Although you have to keep in mind that the payload or the class that implements DeferredTask will want to serialize whats included the task. For those who use injection will need to use something like static injection.

1. create a class that implements DeferredTask
2. create a method that wills tart your task.

1. Create a class that implements the interface DeferredTask

import com.google.appengine.api.taskqueue.DeferredTask;

public class DemoDeferredTask implements DeferredTask {
 
private String dothis;

 
public DemoDeferredTask(String dothis) {
   
this.dothis = dothis;
 
}
 
 
@Override
 
public void run() {
 
}

}

2. Start your task like this

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

 
public void startTask() {
   
String dothis = "pass in something";
   
DemoDeferredTask payload = new DemoDeferredTask(dothis);
   
   
TaskOptions options = TaskOptions.Builder.withPayload(payload);
   
Queue que = QueueFactory.getDefaultQueue();
    que
.add(options);
 
}

B. This is my method to starting a task with a servlet

1. Setup the path to my task servlet in web.xml
2. Setup a class to start the task servlet. 
3. Run your classes in your task.

1. WEB-INF/web.xml

Create the path to the task starting servlet.
        <servlet>
               
<servlet-name>appenginetask</servlet-name>
               
<servlet-class>org.gonevertical.server.servlet.ServletRunAppEngineTask</servlet-class>
       
</servlet>
       
<servlet-mapping>
               
<servlet-name>appenginetask</servlet-name>
               
<url-pattern>/task</url-pattern>
       
</servlet-mapping>

2. Task Starting

This is how I start my tasks which could be done from cron or client button.

import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.gonevertical.server.jdo.TaskJdo;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

public class StartAppEngineTask {

 
private static final Logger log = Logger.getLogger(StartAppEngineTask.class.getName());

 
private TaskJdo taskJdo;
 
 
public TaskJdo run(TaskType taskType, HashMap<String, String> parameters) {
   
String url = createTask(taskType, parameters);
   
try {
     
TaskOptions taskOptions = TaskOptions.Builder.withUrl(url).method(Method.GET);
     
Queue queue = QueueFactory.getDefaultQueue();
      queue
.add(taskOptions);
   
} catch (Exception e) {
      log
.log(Level.SEVERE, "run task error=", e);
      removeTask
();
   
}
   
return taskJdo;
 
}
 
 
public TaskJdo run(TaskType taskType, HashMap<String, String> parameters, String queueName) {
   
String url = createTask(taskType, parameters);
   
try {
     
TaskOptions taskOptions = TaskOptions.Builder.withUrl(url).method(Method.GET);
     
Queue queue = QueueFactory.getQueue(queueName);
      queue
.add(taskOptions);
   
} catch (Exception e) {
      log
.log(Level.SEVERE, "run task error=", e);
      removeTask
();
   
}
   
return taskJdo;
 
}

 
public TaskJdo run(HttpServletRequest request, TaskType task, HashMap<String, String> parameters) {
   
String url = createTask(task, parameters);
   
try {
     
TaskOptions taskOptions = TaskOptions.Builder.withUrl(url).header("Cookie", request.getHeader("Cookie")).method(Method.GET);
     
Queue queue = QueueFactory.getDefaultQueue();
      queue
.add(taskOptions);
   
} catch (Exception e) {
      log
.log(Level.SEVERE, "run task error=", e);
      removeTask
();
   
}
   
return taskJdo;
 
}
 
 
public TaskJdo run(HttpServletRequest request, TaskType taskType, HashMap<String, String> parameters, String queueName) {
   
String url = createTask(taskType, parameters);
   
try {
     
TaskOptions taskOptions = TaskOptions.Builder.withUrl(url).header("Cookie", request.getHeader("Cookie")).method(Method.GET);
     
Queue queue = QueueFactory.getQueue(queueName);
      queue
.add(taskOptions);
   
} catch (Exception e) {
      log
.log(Level.SEVERE, "run task error=", e);
      removeTask
();
   
}
   
return taskJdo;
 
}
 
 
private String createTask(TaskType taskType, HashMap<String, String> parameters) {
    taskJdo
= new TaskJdo();
    taskJdo
.setTaskType(taskType);
    taskJdo
.persist();
   
if (parameters == null) {
      parameters
= new HashMap<String, String>();
   
}
    parameters
.put("taskId", taskJdo.getId());
   
String url = "/task?" + getSerializedParameters(parameters);;
   
return url;
 
}
 
 
private String getSerializedParameters(HashMap<String, String> params) {
   
if (params == null) {
     
return "";
   
}
   
String s = "";
   
Collection<String> keys = params.keySet();
   
for (String key: keys){
     
String value = params.get(key);
      s  
+= "&" + key + "=" + value;
   
}
   
return s;
 
}
 
 
private void removeTask() {
   
if (taskJdo == null) {
     
return;
   
}
    taskJdo
.remove();
 
}
 
}

3. Starting Tasks in Servlet

This is my task manager which starts the task. I also create a entity representing the task.
public class ServletRunAppEngineTask extends HttpServlet {
 
 
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
   
String id = request.getParameter("taskId");
   
TaskJdo taskJdo = isTaskLegit(id);
   
if (taskJdo == null) {
     
return;
   
}
   
   
if (taskJdo.getTaskType() == TaskType.CODESIMPORT) {
      runCodesImport
(taskJdo);
   
}
 
}
 
 
private TaskJdo isTaskLegit(String taskId) {
   
if (taskId == null) {
     
return null;
   
}
   
TaskJdo task = TaskJdo.findTaskJdo(taskId);
   
return task;
 
}

 
private void runCodesImport(TaskJdo taskJdo) {
   
ProcessCodes process = new ProcessCodes();
    process
.runProcessCodes(taskJdo);
 
}
 
}

Utility Classes - TaskType

public enum TaskType {
  CODESIMPORT
;
 
 
public String value() {
   
return name().toLowerCase();
 
}
 
public static TaskType fromValue(String v) {
   
return valueOf(v.toUpperCase());
 
}
}

Utility Classes - TaskJdo

@PersistenceCapable
public class TaskJdo {
 
 
private static final Logger log = Logger.getLogger(TaskJdo.class.getName());
 
 
public static TaskJdo findTaskJdo(String id) {
   
return RequestFactoryUtilsJdo.find(TaskJdo.class, id);
 
}
 
 
public static TaskJdo createTask() {
   
TaskJdo t = new TaskJdo();
    t
.persist();
   
return t;
 
}
 
 
public static TaskJdo runTask(TaskJdoFilter filter) {
   
StartAppEngineTask startTask = new StartAppEngineTask();
   
   
TaskJdo taskJdo = null;
   
if (filter.getProcessCodes() != null && filter.getProcessCodes() == true) {
      taskJdo
= startTask.run(TaskType.CODESIMPORT, null);
   
}
   
   
return taskJdo;
 
}
 
 
public static TaskJdo findTaskJdoFromLong(Long id) {
   
TaskJdo d = RequestFactoryUtilsJdo.find(TaskJdo.class, id);
   
return d;
 
}

 
public static List<TaskJdo> findTaskList(TaskJdoFilter filter) {
   
ArrayList<Filter> tfilter = null;
   
if (filter.getSearch() != null) {
      tfilter
= new ArrayList<Filter>();
     
List<String> searchList = filter.getSearch();
     
Iterator<String> itr = searchList.iterator();
     
while(itr.hasNext()) {
       
String s = itr.next();
       
if (s != null) {
          s
= s.toLowerCase().trim();
         
Filter f = new Filter("search", FilterOperator.EQUAL, s);
          tfilter
.add(f);
       
}
     
}
   
}
   
   
if (filter.getLimit() == 0) {
     
System.out.println("Did you forget to set the limit? !!!!!!!!");
   
}

   
List<TaskJdo> list = RequestFactoryUtilsJdo.findList(TaskJdo.class, tfilter, filter.getOffset(), filter.getLimit());
   
if (list == null) {
      list
= new ArrayList<TaskJdo>();
   
}
   
return list;
 
}

 
public static Long findCount(TaskJdoFilter filter) {
   
ArrayList<Filter> tfilter = null;
   
if (filter.getSearch() != null) {
      tfilter
= new ArrayList<Filter>();
     
List<String> searchList = filter.getSearch();
     
Iterator<String> itr = searchList.iterator();
     
while(itr.hasNext()) {
       
String s = itr.next();
       
if (s != null) {
          s
= s.toLowerCase().trim();
         
Filter f = new Filter("search", FilterOperator.EQUAL, s);
          tfilter
.add(f);
       
}
     
}
   
}

   
Long count = RequestFactoryUtilsJdo.findCount(TaskJdo.class, tfilter);
   
return count;
 
}
 
 
 

 
@PrimaryKey
 
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
 
private Key key;
 
 
@Persistent
 
private Long version;

 
@Persistent
 
private Date dateCreated;

 
@Persistent
 
private TaskType taskType;

 
@Persistent
 
private Boolean finished;
 
 
@Persistent
 
private Date dateFinished;

 
@Persistent
 
private HashSet<HashMapJdo> parameters;

 
@Persistent
 
private Text note;
 
 
@Persistent
 
private Text error;
 
 
 
public void setId(String id) {
   
if (id == null) {
     
return;
   
}
    key
= KeyFactory.stringToKey(id);
 
}
 
public String getId() {
   
String id = null;
   
if (key != null) {
      id
= KeyFactory.keyToString(key);
   
}
   
return id;
 
}
 
public Long getIdLong() {
   
Long id = null;
   
if (key != null) {
      id
= key.getId();
   
}
   
return id;
 
}

 
public void setVersion(Long version) {
   
this.version = version;
 
}
 
public Long getVersion() {
   
if (version == null) {
      version
= 0l;
   
}
   
return version;
 
}
 
private void incrementVersion() {
   
if (version == null) {
      version
= 0l;
   
} else {
      version
++;
   
}
 
}
 
 
private void setDateCreated() {
   
if (dateCreated == null) {
      dateCreated
= new Date();
   
}
 
}
 
public Date getDateCreated() {
   
return this.dateCreated;
 
}
 
 
public void setTaskType(TaskType taskType) {
   
this.taskType = taskType;
 
}
 
public TaskType getTaskType() {
   
return taskType;
 
}

 
public void setDateFinished(Date dateFinished) {
   
this.dateFinished = dateFinished;
 
}
 
public Date getDateFinished() {
   
return dateFinished;
 
}
 
 
public void setFinished(Boolean finished) {
   
this.finished = finished;
 
}
 
public Boolean getFinished() {
   
return finished;
 
}
 
 
public void setParameters(HashSet<HashMapJdo> parameters) {
   
this.parameters = parameters;
 
}
 
public HashSet<HashMapJdo> getParameters() {
   
return parameters;
 
}
 
 
public void setNote(String note) {
   
if (note == null) {
     
this.note = null;
   
} else {
     
this.note = new Text(note);
   
}
 
}
 
public String getNote() {
   
if (note == null) {
     
return null;
   
} else {
     
return note.getValue();
   
}
 
}
 
 
public void setError(String error) {
   
if (error == null) {
     
this.error = null;
   
} else {
     
this.error = new Text(error);
   
}
 
}
 
public String getError() {
   
if (error == null) {
     
return null;
   
} else {
     
return error.getValue();
   
}
 
}
 
 
public TaskJdo persist() {
    incrementVersion
();
    setDateCreated
();
   
return RequestFactoryUtilsJdo.persist(this);
 
}
 
public boolean remove() {
   
return RequestFactoryUtilsJdo.remove(this);
 
}
 
 
 
public String toString() {
   
String s = "";
    s
+= "key=" + key + " ";
    s
+= "taskType=" + taskType + " ";
    s
+= "dateCreated=" + dateCreated + " ";
    s
+= "finished=" + finished + " ";
    s
+= "dateFinished=" + finished + " ";
    s
+= "hashmap={ " + parameters + " } ";
   
return s;
 
}  

}







Comments