0
votes

I am new to Google Cloud Tasks.

I refer to https://cloud.google.com/tasks/docs/quickstart-appengine.

I have successfully set up the Java sample app, created an App Engine queue and added a task to the App Engine queue.

However, as far as I understand, that sample app actually does nothing. Where do I put my code, if I want the app to do something useful?

1

1 Answers

1
votes

Following the Java sample app, your code should be placed in TaskServlet.java.

The payload you send is going to be taken by the handler, where the piece of code you want to execute is going to be. You can use there that payload to execute your code.

Here is how my code looks like:

@WebServlet(
name = "Tasks",
description = "Create Cloud Task",
urlPatterns = "/tasks/create" //Relative path to this handler
)
public class TaskServlet extends HttpServlet {
  private static Logger log = Logger.getLogger(TaskServlet.class.getName());

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws 
    IOException {
    log.info("Received task request: " + req.getServletPath());
    String body = req.getReader()
        .lines()
        .reduce("", (accumulator, actual) -> accumulator + actual);

    if (!body.isEmpty()) {
      log.info("Request payload: " + body);
      String output = String.format("Received task with payload %s", body);
      resp.getOutputStream().write(output.getBytes());
      log.info("Sending response: " + output);

      //For instance, something like...
      myFunction(body); //body being the payload

      resp.setStatus(HttpServletResponse.SC_OK);
    } else {
      log.warning("Null payload received in request to " + req.getServletPath());
    }
  }

  private void myFunction(String str){
    //Your code here
  }

}

Within CreateTask.java observe how the relative path to the handler is set:

// Construct the task body.
  Task.Builder taskBuilder = Task
      .newBuilder()
      .setAppEngineHttpRequest(AppEngineHttpRequest.newBuilder()
          .setBody(ByteString.copyFrom(payload, Charset.defaultCharset()))
          .setRelativeUri("/tasks/create") //This will look for a handler with this relative path
          .setHttpMethod(HttpMethod.POST)
          .build());

You can also create different handlers, giving them different relative URI.