9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Queueableインターフェースを実装したクラスでCalloutを呼ぶ

Posted at

TL;DR

ここに書いてありました。

Queueableを採用した理由

とある事情で@futureメソッドから@futureメソッドが呼ばれてしまうことがあり、Future method cannnot be called from a future or batch methodの制限に引っかかってしまったためです。

最初の実装

シンプルにこんな具合で実装しました。

public with sharing class MyQueueableClass implements Queueable {
  public void execute(QueueableContext context) {
    Http httpClient = new Http();

    HttpRequest request = new HttpRequest();
    request.setEndpoint('http://example.com');
    request.setMethod('GET');
    HttpResponse response = httpClient.send(request);

    MyCustomObject__c record = new MyCustomObject__c(
      ResponseBody__c = response.getBody()
    );
    insert record;
  }
}

しかし実行すると、Callout not allowed from this future method. Please enable callout by annotating the future method. eg: @Future(callout=true)というメッセージが…。

解決法

最初にご紹介した記事の返信の通り、Database.AllowsCalloutsimplementsします。

public with sharing class MyQueueableClass implements Queueable, Database.AllowsCallouts {
  public void execute(QueueableContext context) {
    Http httpClient = new Http();

    HttpRequest request = new HttpRequest();
    request.setEndpoint('http://example.com');
    request.setMethod('GET');
    HttpResponse response = httpClient.send(request);

    MyCustomObject__c record = new MyCustomObject__c(
      ResponseBody__c = response.getBody()
    );
    insert record;
  }
}

さいごに

Salesforceには知らない仕様や機能がまだまだたくさんあるなぁ、と再確認させられました。
あとDeveloper Communityはとても有用ですね。

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?