How to cancel a Cron scheduled workflow gracefully

I have started a workflow by set CronSchedule in StartWorkflowOptions. Ideally I want to stop the schedule for next run, but the current execution shall continue until the last activity.
Using client.CancelWorkflow() will stop workflow straight away. Not sure if there’s any trick to achieve the stop scheduled periodic workflow gracefully?

I don’t think CancelWorkflow stops it right away. TerminateWorkflow does.

CancelWorkflow will stop the workflow, but it will allow the running activity to finish, but the remaining activities will be skipped. TerminateWorkflow will terminate the the running activity and workflow right away.

but the remaining activities will be skipped.

This is not really true. The CancelWorkflow cancels the workflow.Context passed to the workflow. If you want all the activities executed independently of the cancellation pass into them a context created through workflow.NewDisconnectedContext.

It seems that every activity inside the workflow has to be ready to rerun itself with DisconnectedContext, based on the docs.
Is it the correct understanding? e.g. It means that activity2 finishes its execution with disconnected context, activity3/4 etc. has to run with the same disconnected context in order to continue

You can just ignore the cancellation request completely by running all the activities using the disconnected context:

func MyWorkflow() {
    ctx = workflow.NewDisconnectedContext(ctx)
      ... 
      workflow.ExecuteActivity(ctx, Activity1).Get(ctx, ...)
      ... 
      workflow.ExecuteActivity(ctx, Activity2).Get(ctx, ...)
      ... 
      workflow.ExecuteActivity(ctx, Activity3).Get(ctx, ...)
      ... 
      workflow.ExecuteActivity(ctx, Activity4).Get(ctx, ...)
}

How we can achieve this using java sdk?

@Pritam_Kumar2 Would you ask the question in a separate forum post? This one is marked with go-sdk tag.

Sure @maxim.

I have a cron workflow which has no activities. When I cancel it, I see that it marks the currently running workflow as failed and creates a new one. Is this expected?

Correction to my comment above. When I cancel the workflow, it just marks it complete and creates a new one.

I believe currently cancellation applies to the currently running cron iteration. So you have to call Terminate to kill the cron itself. We know that it is pretty limiting and plan to work on a better cron experience.

You can always code your periodic workflow yourself using loops and continue as new.