|
| 1 | +/* |
| 2 | + * Copyright 2019 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.task; |
| 18 | + |
| 19 | +// [START taskqueues_new_task] |
| 20 | +import com.google.cloud.tasks.v2.AppEngineHttpRequest; |
| 21 | +import com.google.cloud.tasks.v2.CloudTasksClient; |
| 22 | +import com.google.cloud.tasks.v2.HttpMethod; |
| 23 | +import com.google.cloud.tasks.v2.QueueName; |
| 24 | +import com.google.cloud.tasks.v2.Task; |
| 25 | +import com.google.protobuf.ByteString; |
| 26 | +import java.nio.charset.Charset; |
| 27 | + |
| 28 | +public class CreateTask { |
| 29 | + public static void createTask(String projectId, String locationId, String queueId) |
| 30 | + throws Exception { |
| 31 | + try (CloudTasksClient client = CloudTasksClient.create()) { |
| 32 | + // TODO(developer): Uncomment these lines and replace with your values. |
| 33 | + // String projectId = "your-project-id"; |
| 34 | + // String locationId = "us-central1"; |
| 35 | + // String queueId = "default"; |
| 36 | + String key = "key"; |
| 37 | + |
| 38 | + // Construct the fully qualified queue name. |
| 39 | + String queueName = QueueName.of(projectId, locationId, queueId).toString(); |
| 40 | + |
| 41 | + // Construct the task body. |
| 42 | + Task taskParam = |
| 43 | + Task.newBuilder() |
| 44 | + .setAppEngineHttpRequest( |
| 45 | + AppEngineHttpRequest.newBuilder() |
| 46 | + .setRelativeUri("/worker?key=" + key) |
| 47 | + .setHttpMethod(HttpMethod.GET) |
| 48 | + .build()) |
| 49 | + .build(); |
| 50 | + |
| 51 | + Task taskPayload = |
| 52 | + Task.newBuilder() |
| 53 | + .setAppEngineHttpRequest( |
| 54 | + AppEngineHttpRequest.newBuilder() |
| 55 | + .setBody(ByteString.copyFrom(key, Charset.defaultCharset())) |
| 56 | + .setRelativeUri("/worker") |
| 57 | + .setHttpMethod(HttpMethod.POST) |
| 58 | + .build()) |
| 59 | + .build(); |
| 60 | + |
| 61 | + // Send create task request. |
| 62 | + Task[] tasks = new Task[] {taskParam, taskPayload}; |
| 63 | + for (Task task : tasks) { |
| 64 | + Task response = client.createTask(queueName, task); |
| 65 | + System.out.println(response); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | +// [END taskqueues_new_task] |
0 commit comments