I have a queueable class that is triggered from a trigger that makes a callout. I wanted to use Queueable for scenarios where I need to insert 3-5k of records and eventually make 3-5k callouts. But the queueable goes into a loop even when I insert only 5 records and it takes so long to abort the job once it's started. any help is appreciated
trigger LeadTrigger on Lead (before insert, before update) {
List<Id> userIds = new List<Id>();
for (Lead objLead : Trigger.new) {
if(!System.isFuture() || !System.isQueueable()){
userIds.add(objLead.Id);
}
}
if (userIds != null && (!System.isFuture() || !System.isQueueable())) {
System.enqueueJob(new KeyApiQueueable (userIds));
}
}
Queueable
public with sharing class KeyApiQueueable implements Queueable, Database.AllowsCallouts {
public List<Id> recordIds;
public KeyApiQueueable (list<id> ids){
this.recordIds = ids;
}
public void execute(QueueableContext context) {
Lead[] leadsToUpdate = new lead[0];
while(recordIds.size() > 0 && leadsToUpdate.size() < 100) { // Max 100 callouts allowed here
Id nextId = recordIds.remove(0);
leadsToUpdate.add(processPayload(nextId));
}
update leadsToUpdate;
if(recordIds.size() > 0) {
System.enqueueJob(this);
}
}
public static Lead processPayload(Id recordId){
List<Lead> leadAccount = [SELECT Id, deger1__c, deger2__c FROM Lead WHERE Id =: recordId];
Lead leadAccounts = leadAccount[0];
Integer Value2;
Integer Value3;
HttpRequest request= new HttpRequest();
request.setMethod('GET');
request.setEndPoint('https://api.spoonacular.com/recipes/69095/tasteWidget.json?apiKey=b454430f54a14e');
try{
Http http=new Http();
HttpResponse response=http.send(request);
if (response.getStatusCode() == 200) {
Map<String,Object> results = (Map<String,Object>)Json.deserializeUntyped(response.getBody());
Value2= Integer.valueof(results.get('sweetness'));
Value3 = Integer.valueof(results.get('saltiness'));
}
leadAccounts.deger1__c = Value3;
leadAccounts.deger2__c = Value2;
}
catch(System.CalloutException e){
system.debug('Error-' + e.getMessage());
}
return leadAccounts;
}
}