Safe way to compute the duration to sleep

I have a situation where I want to compute the duration to put the workflow to sleep before running any activities. Is it safe for my workflow method to do something like:

Workflow.sleep(Duration.ofHours(Duration.between(from, to).toHours()))

Here from = ZonedDateTime.now(), and to = ZonedDateTime retrieved from DB and passed into the workflow method.

My intuition is it isn’t deterministic and therefore unsafe. If so, how do I make this safe?

Here from = ZonedDateTime.now(), and to = ZonedDateTime retrieved from DB and passed into the workflow method.

What do you mean by passed to the workflow method? If they are passed as workflow arguments or returned as an activity result then they are recorded and the code will be deterministic.

In the most cases Workflow.currentTimeMillis() is the best way to get the current time.

You can also use Workflow.getInfo().getRunStartedTimestampMillis() to get the time workflow was started.

Thanks Maxim. I will call Workflow.currentTimeMillis() in the workflow method to get “now”. That solves the problem.

1 Like