Example of using Workflow newTimer function

Hello, I’m looking for an example of using the Workflow newTimer function. I didn’t find anything about it in the temporal-java-samples project. Ideally, this response should include a simple example using the Java SDK, but if you know the answer using any other SDK, I appreciate your help.

The context, suppose the following use case:

  1. Send an email to the user with a validation token.
  2. Set a timer to cancel the workflow if the token is not confirmed in a specific amount of time.

Implementing the interaction with the user is very simple, we just need to use signals. I don’t know how to set the timer in item (2).

You don’t need newTimer for this use case. I would use workflow.await instead:

activities.sendEmail(validationToken);
// confirmationReceived is set by the signal handler
if (workflow.await(confirmationTimeout, ()->confirmationReceived)) {
 // handle confirmation
} else {
 // handle timed out
}
1 Like

Hi @maxim, thank you so much for the information. That worked very well. When gracefully handling the timeouts like in the example you gave, the workflow is marked as “Completed”, and I think that is the right thing to do because the workflow has completed its job, with an outcome of “Confirmation timeout”.

I’m returning the status in the workflow method so that we can see if there was a timeout or not:

activities.sendEmail(validationToken);
// confirmationReceived is set by the signal handler
if (workflow.await(confirmationTimeout, ()->confirmationReceived)) {
 // handle confirmation
 return "Success"
} else {
 return "Confirmation timeout"
}
if (workflow.await(confirmationTimeout, ()->confirmationReceived)) {
 // handle confirmation
 return "Success"
} else {
 return "Confirmation timeout"
}

I think another option could be to check if confirmationReceived is true/false as
the workflow.await says "wait until either the confirmationTimeout fires or confirmationReceived becomes true.

So something like


workflow.await(confirmationTimeout, ()->confirmationReceived)
if(confirmationReceived) { ... success  ...} else { ...timeout ...}
1 Like

Thanks for your suggestion.