Temporal Worker

In day-to-day conversations, the term Worker is used to denote both a Worker Program, the static code that defines the constraints of the Worker Process, developed using the APIs of a Temporal SDK, and a Worker Process, responsible for polling a Task Queue, dequeueing a Task, executing your code in response to a Task, and responding to the Temporal Server with the results.. Temporal documentation aims to be explicit and differentiate between them.

Workers execute the Workflow code. The Worker itself is provided by the Temporal SDK. When tat code executes, the Worker establishes a persistent connection to the Temporal Cluster and begins polling a Task Queue.

Initialing a Worker

There are typically three things you need in order to configure a Worker:

  1. A Temporal Client, which is used to communicate with the Temporal Cluster
  2. The name of a Task Queue, which is maintained by the Temporal Server and polled by the Worker
  3. The name of the Workflow Definition interface, used to register the Workflow implementation with the Worker
package io.temporal.learn;
 
import io.temporal.client.WorkflowClient;
import io.temporal.serviceclient.WorkflowServiceStubs;
import io.temporal.worker.Worker;
import io.temporal.worker.WorkerFactory;
 
public class GreetingWorker {
 
    public static void main(String[] args) {
        // Adequat for local development, but if Temporal Server is hosted in remote, you
        // will use `WorkflowServiceStubs.newLocalServiceStubs(options)` instead, where
        // the options will contain the host and port to reach its frontend service.
        WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs();
        WorkflowClient client = WorkflowClient.newInstance(service);
        WorkerFactory factory = WorkerFactory.newInstance(client);
 
        // Specify the name of the Task Queue that this Worker should poll
        Worker worker = factory.newWorker("greeting-tasks");
 
        // Specify which Workflow implementations this Worker will support
        worker.registerWorkflowImplementationTypes(GreetingImpl.class);
 
        // Begin running the Worker
        factory.start();
    }
}