# Cancel or pause a scheduled send

## API Overview

Using the Cancel Scheduled Sends API, you can cancel or pause sending one or more groups of emails. SendGrid defines these multiple scheduled send requests together as batches identified with a `batch_id`.

With this API, you can perform the following tasks on scheduled emails:

* Define and validate the ID for a batch of messages.
* Retrieve, update, pause, resume, or cancel a scheduled send.

Cancelling or pausing a batch of messages include the following conditions:

* You can't pause or cancel more than 10 different batches at one time.
* You can't pause or cancel a batch later than 10 minutes before the scheduled `send_at` time.
* When you cancel or pause a batch, all messages associated with that batch stay in your sending queue.
* When a cancelled batch reaches its `send_at` time, SendGrid discards the messages.
* When a paused batch reaches its `send_at` time, SendGrid retains the messages.
  When you resume a paused batch, SendGrid delivers your scheduled send.
* When a paused batch passes 72 hours after its `send_at` time, SendGrid discards the messages as *Expired*.

To cancel a scheduled send of a single message, consult [Canceling a Scheduled Send][cancel-send].

[cancel-send]: /docs/sendgrid/for-developers/sending-email/stopping-a-scheduled-send/

## Operation overview

```json
{"path":"https://api.sendgrid.com/v3/user/scheduled_sends","method":"post","servers":[{"url":"https://api.sendgrid.com","description":"for global users and subusers"},{"url":"https://api.eu.sendgrid.com","description":"for EU regional subusers"}]}
```

**This endpoint allows you to cancel or pause a scheduled send associated with a `batch_id`.**

Passing this endpoint a `batch_id` and status will cancel or pause the scheduled send.

Once a scheduled send is set to `pause` or `cancel` you must use the "Update a scheduled send" endpoint to change its status or the "Delete a cancellation or pause from a scheduled send" endpoint to remove the status. Passing a status change to a scheduled send that has already been paused or cancelled will result in a `400` level status code.

If the maximum number of cancellations/pauses are added to a send, a `400` level status code will be returned.

## Operation details

### Authentication

API Key

### Headers

```json
[{"in":"header","name":"Authorization","required":true,"default":"Bearer <<YOUR_API_KEY_HERE>>","schema":{"type":"string"}},{"name":"on-behalf-of","in":"header","description":"The `on-behalf-of` header allows you to make API calls from a parent account on behalf of the parent's Subusers or customer accounts. You will use the parent account's API key when using this header. When making a call on behalf of a customer account, the property value should be \"account-id\" followed by the customer account's ID (e.g., `on-behalf-of: account-id <account-id>`). When making a call on behalf of a Subuser, the property value should be the Subuser's username (e.g., `on-behalf-of: <subuser-username>`). See [**On Behalf Of**](/docs/sendgrid/api-reference/how-to-use-the-sendgrid-v3-api/on-behalf-of) for more information.","required":false,"schema":{"type":"string"},"refName":"#/components/parameters/OnBehalfOf","modelName":"__components_parameters_OnBehalfOf"}]
```

### Request body

```json
{"schema":{"title":"Cancel or pause a scheduled send request","type":"object","required":["batch_id","status"],"example":{"batch_id":"YOUR_BATCH_ID","status":"pause"},"properties":{"batch_id":{"type":"string","description":"The batch ID is the identifier that your scheduled mail sends share.","pattern":"^[a-zA-Z0-9]"},"status":{"type":"string","default":"pause","description":"The status of the send you would like to implement. This can be pause or cancel. To delete a pause or cancel status see DELETE /v3/user/scheduled_sends/{batch_id}","enum":["pause","cancel"],"refName":"Status","modelName":"Status"}}},"encodingType":"application/json"}
```

### Responses

```json
[{"responseCode":"201","schema":{"description":"","content":{"application/json":{"schema":{"title":"User Scheduled Send status","example":{"batch_id":"HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi","status":"pause"},"type":"object","required":["batch_id","status"],"refName":"ScheduledSendStatus","modelName":"ScheduledSendStatus","properties":{"batch_id":{"type":"string","pattern":"^[a-zA-Z0-9\\-\\_]"},"status":{"type":"string","description":"The status of the scheduled send.","enum":["cancel","pause"],"refName":"Status2","modelName":"Status2"}}}}}}},{"responseCode":"400","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/ScheduledSends400","modelName":"__components_responses_ScheduledSends400"}},{"responseCode":"401","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/ScheduledSends401","modelName":"__components_responses_ScheduledSends401"}},{"responseCode":"403","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/ScheduledSends403","modelName":"__components_responses_ScheduledSends403"}},{"responseCode":"404","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","example":{"errors":[{"field":"field_name","message":"error message"}]},"refName":"ErrorResponse","modelName":"ErrorResponse","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string","description":"An error message."},"field":{"description":"When applicable, this property value will be the field that generated the error.","nullable":true,"type":"string"},"help":{"type":"object","description":"When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error."}}}},"id":{"type":"string","description":"When applicable, this property value will be an error ID."}}}}},"refName":"#/components/responses/ScheduledSends404","modelName":"__components_responses_ScheduledSends404"}},{"responseCode":"500","schema":{"description":"","content":{"application/json":{"schema":{"type":"object","properties":{"errors":{"type":"array","items":{"type":"object","properties":{"message":{"type":"string"}}}}}}}},"refName":"#/components/responses/ScheduledSends500","modelName":"__components_responses_ScheduledSends500"}}]
```

Cancel or pause a scheduled send

```js
const client = require("@sendgrid/client");
client.setApiKey(process.env.SENDGRID_API_KEY);

const data = {
  batch_id: "YOUR_BATCH_ID",
  status: "pause",
};

const request = {
  url: `/v3/user/scheduled_sends`,
  method: "POST",
  body: data,
};

client
  .request(request)
  .then(([response, body]) => {
    console.log(response.statusCode);
    console.log(response.body);
  })
  .catch((error) => {
    console.error(error);
  });
```

```python
import os
from sendgrid import SendGridAPIClient


sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))

data = {"batch_id": "YOUR_BATCH_ID", "status": "pause"}

response = sg.client.user.scheduled_sends.post(request_body=data)

print(response.status_code)
print(response.body)
print(response.headers)
```

```csharp
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SendGrid;

public class Program {
    public static async Task Main() {
        string apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
        var client = new SendGridClient(apiKey);

        var data =
            @"{
            ""batch_id"": ""YOUR_BATCH_ID"",
            ""status"": ""pause""
        }";

        var response = await client.RequestAsync(
            method: SendGridClient.Method.POST, urlPath: "user/scheduled_sends", requestBody: data);

        Console.WriteLine(response.StatusCode);
        Console.WriteLine(response.Body.ReadAsStringAsync().Result);
        Console.WriteLine(response.Headers.ToString());
    }
}
```

```java
import com.sendgrid.*;
import java.io.IOException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Arrays;

public class Example {
    public static void main(String[] args) throws IOException {
        try {
            SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint("/user/scheduled_sends");
            request.setBody(new JSONObject(new HashMap<String, Object>() {
                {
                    put("batch_id", "YOUR_BATCH_ID");
                    put("status", "pause");
                }
            }).toString());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
}
```

```go
package main

import (
	"fmt"
	"github.com/sendgrid/sendgrid-go"
	"os"
)

func main() {
	apiKey := os.Getenv("SENDGRID_API_KEY")
	host := "https://api.sendgrid.com"
	request := sendgrid.GetRequest(apiKey, "/v3/user/scheduled_sends", host)
	request.Method = "POST"
	request.Body = []byte(`{
  "batch_id": "YOUR_BATCH_ID",
  "status": "pause"
}`)
	response, err := sendgrid.API(request)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		fmt.Println(response.StatusCode)
		fmt.Println(response.Body)
		fmt.Println(response.Headers)
	}
}
```

```php
<?php
// Uncomment the next line if you're using a dependency loader (such as Composer) (recommended)
// require 'vendor/autoload.php';

// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';

$apiKey = getenv("SENDGRID_API_KEY");
$sg = new \SendGrid($apiKey);
$request_body = json_decode('{
    "batch_id": "YOUR_BATCH_ID",
    "status": "pause"
}');

try {
    $response = $sg->client
        ->user()
        ->scheduled_sends()
        ->post($request_body);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $ex) {
    echo "Caught exception: " . $ex->getMessage();
}
```

```ruby
require 'sendgrid-ruby'
include SendGrid

sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
data = JSON.parse('{
  "batch_id": "YOUR_BATCH_ID",
  "status": "pause"
}')

response = sg.client.user.scheduled_sends.post(request_body: data)
puts response.status_code
puts response.headers
puts response.body
```

```bash
curl -X POST "https://api.sendgrid.com/v3/user/scheduled_sends" \
--header "Authorization: Bearer $SENDGRID_API_KEY" \
--header "Content-Type: application/json" \
--data '{"batch_id": "YOUR_BATCH_ID", "status": "pause"}'
```
