A Java Task Queue Example

The following code adds a task to a queue with options.

In index.html:

<!-- A basic index.html file served from the "/" URL. -->
<html>
<body>
<p>Enqueue a value, to be processed by a worker.</p>
<form action="/enqueue" method="post">
    <input type="text" name="key">
    <input type="submit">
</form>
</body>
</html>

In Enqueue.java:

// The Enqueue servlet should be mapped to the "/enqueue" URL.
public class Enqueue extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    String key = request.getParameter("key");

    // Add the task to the default queue.
    Queue queue = QueueFactory.getDefaultQueue();
    queue.add(TaskOptions.Builder.withUrl("/worker").param("key", key));

    response.sendRedirect("/");
  }
}

In Worker.java:

// The Worker servlet should be mapped to the "/worker" URL.
public class Worker extends HttpServlet {
  private static final Logger log = Logger.getLogger(Worker.class.getName());

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    String key = request.getParameter("key");

    // Do something with key.
    // ...
  }
}

Tasks added to this queue will execute by calling the request handler at the URL /worker with the parameter key. They will execute at the rate set in the queue.xml file, or the default rate of 5 tasks per second.