Esempio di coda di attività Java

Il seguente codice aggiunge un'attività a una coda con opzioni.

Tra 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>

Tra Enqueue.java:

// The Enqueue servlet should be mapped to the "/enqueue" URL.
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(
    name = "TaskEnque",
    description = "taskqueue: Enqueue a job with a key",
    urlPatterns = "/taskqueues/enqueue"
)
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("/");
  }
}

Tra Worker.java:

// The Worker servlet should be mapped to the "/worker" URL.
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(
    name = "TaskWorker",
    description = "TaskQueues: worker",
    urlPatterns = "/taskqueues/worker"
)
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.
    // ...
  }
}

Le attività aggiunte a questa coda verranno eseguite chiamando il gestore delle richieste all'URL /worker con il parametro key. Verranno eseguite alla velocità impostata nel file queue.xml o alla velocità predefinita di 5 attività al secondo.