Deleplace
Deleplace

Reputation: 7772

How do I specify an execution delay with the Google Cloud Tasks Go client library?

I followed this documentation to create a task, and read "You can also fine-tune the configuration for the task, like scheduling a time in the future when it should be executed".

However it's still not clear to me how to effectively schedule the execution in a delay (a time.Duration) chosen by me, e.g. "please trigger the cleanup of these objects in 20 minutes".

The relevant LOCs are the CreateTaskRequest creation, and the Task creation:

        req := &taskspb.CreateTaskRequest{
                Parent: queuePath,
                Task: &taskspb.Task{
                        MessageType: &taskspb.Task_HttpRequest{
                                HttpRequest: &taskspb.HttpRequest{
                                        HttpMethod: taskspb.HttpMethod_POST,
                                        Url:        url,
                                },
                        },
                },
        }
        createdTask, err := client.CreateTask(ctx, req)

Should I consider using Cloud Scheduler for this?

Upvotes: 2

Views: 3425

Answers (1)

Deleplace
Deleplace

Reputation: 7772

You don't need Cloud Scheduler for this.

What you're looking for is the field tasks.Task.ScheduleTime, which has type *timestamppb.Timestamp.

Converting your time.Duration into a *timestamppb.Timestamp date in the future is pretty straightforward (here, ignoring any subsecond precision):

        var d time.Duration = 20 * time.Minute
            
        ts := &timestamppb.Timestamp{
            Seconds: time.Now().Add(d).Unix(),
        },

        req := &taskspb.CreateTaskRequest{
                Parent: queuePath,
                Task: &taskspb.Task{
                        MessageType: &taskspb.Task_HttpRequest{
                                HttpRequest: &taskspb.HttpRequest{
                                        HttpMethod: taskspb.HttpMethod_POST,
                                        Url:        url,
                                },
                        },
                        ScheduleTime: ts,
                },
        }

The above applies to the API v2.

Upvotes: 5

Related Questions