Search code examples
javaworkflowcadence-workflowtemporal-workflowuber-cadence

Uber Cadence (java): How to pause and wait for external signal events?


I have the following dummy workflow code:

The workflow interface:

public interface IMyWorkflow {
    @WorkflowMethod(executionStartToCloseTimeoutSeconds = 60 * 60)
    void begin();
    
    @SignalMethod
    void continueWorkflow();
}

The workflow implementation:

public class MyWorkflowImpl implements IMyWorkflow {
    private final JmsSender sender;
    private static final String QUEUE = "my-queue";

    public void begin() {
        int sum = 0;
                
        // step 1
        sum++;
        sender.sendMessage(QUEUE, "1st call" + sum);
        // PAUSE AND WAIT

        // step 2
        sum++;
        sender.sendMessage(QUEUE, "2nd call" + sum);
        // PAUSE AND WAIT

        // step 3
        sum++;
        sender.sendMessage(QUEUE, "3rd call" + sum);
        // PAUSE AND WAIT
    }

    @Override
    public void continueWorkflow() {
        // 
    }
}

This is the first time that I have used Uber Cadence and for now, I'm stuck on implementation of the pause and wait.

The idea is: that if the workflow is waiting for a signal, an external request must be able to resume the workflow.

Can someone give a hint with some best practices and examples for this scenario?

I did some tests using Workflow.await(() -> false); between the steps, but I've struggled with how to resume the next step.


Solution

  • Here is an example when each change to the sum unblocks the workflow:

    public class MyWorkflowImpl implements IMyWorkflow {
        private final JmsSender sender;
        private static final String QUEUE = "my-queue";
        private int sum;
    
        public void begin() {
            // step 1
            sum++;
            sender.sendMessage(QUEUE, "1st call" + sum);
            // PAUSE AND WAIT
            int before = sum;
            Workflow.await(() -> sum > before);
    
            // step 2
            sum++;
            sender.sendMessage(QUEUE, "2nd call" + sum);
            // PAUSE AND WAIT
            before = sum;
            Workflow.await(() -> sum > before);
    
            // step 3
            sum++;
            sender.sendMessage(QUEUE, "3rd call" + sum);
            // PAUSE AND WAIT
            before = sum;
            Workflow.await(() -> sum > before);
    
        }
    
        @Override
        public void continueWorkflow() {
            sum++;
        }
    }