0

I want to call a method that I have created, that makes HTTP API callout to and fetches data.

Apex method:

@AuraEnabled(cacheable=true)
    public static String events (String webSite, String selectedSiteName, List<String> stringColumns, String date_from, String date_to, String token){
        try{
            // GET API NAMES OF THE SELECTED DIMEONSIONS
            getSites(webSite, token);
            Schema.DescribeFieldResult objFieldDescribe = Object__c.Dimensions__c.getDescribe();
            List<Schema.PicklistEntry> lstPickListValues = objFieldDescribe.getPickListValues();
            String elementValue;
            String elementLabel;
            List<String> apiNamesList = new List<String>();
            for (Schema.PicklistEntry objPickList : lstPickListValues) {
                elementLabel = objPickList.getLabel();
                if (stringColumns.contains(elementLabel)){
                    elementValue = objPickList.getValue();
                    apiNamesList.add(elementValue);
                }
            }
            // CUSTOM ENDPOINT
            String customEndpoint = webSite + 'test';
            // CUSTOM BODY 
            Data data = new Data();
            data.website_id = siteMap.get(selectedSiteName);
            // BODY column
            List<Data.Column> columnWrapper = new List<Data.Column>();
            for (String column_id : apiNamesList) {
                Data.Column c = new Data.Column();
                c.column_id = column_id;
                columnWrapper.add(c);
                //system.debug(column_id + '   c ' + c);
                //system.debug(columnWrapper);
            }
            data.offset = 0;
            data.columns = columnWrapper;
            data.date_from = date_From;
            data.date_to = date_to;
            data.format = 'json';
            // MAKE THE API CALL
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setHeader('Content-Type','application/json');
            req.setHeader('Authorization','Bearer ' + token);
            req.setHeader('Accept-Encoding', 'gzip'); 
            req.setEndpoint(customEndpoint);
            req.setBody(JSON.serialize(data));
            
            Http h = new Http();
            HTTPResponse res = h.send(req);
            
            if (res.getStatusCode() == 200){ 
                Map<String,Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                //List<Object> responseData = (List<Object>) results.get('data');
                // Return data List<Object>
                //System.debug(responseData);
                return res.getBody();
            }
            else {
                System.debug(res.getBody());
                System.debug(res.getStatusCode());
                return null;
            }
        }
        catch (exception ex){
            return null; //return the exception
        }
    }

How can I make this method schedulable, so that I create the job and the user has 'say-so' when to execute this?

What I've tried so far:

    global static void fetchEvents_schedule (String webSite, String selectedSiteName, List<String> stringColumns, String date_from, String date_to, String token, String mode,
                                             String scheduleStartDate_Day, String scheduleStartDate_Month, String scheduleStartDate_Year,
                                             String scheduleEndDate_Day, String scheduleEndDate_Month, String scheduleEndDate_Year, 
                                             String prefferedTime_Minutes,  String prefferedTime_Hour)
    {
        PTEST phca = new PTEST ();
        // Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year
        try {
            if(mode == 'Daily'){
                String CRON_EXP = '0 ' + prefferedTime_Minutes + ' ' + prefferedTime_Hour + ' * ' +  scheduleStartDate_Month + '-' + scheduleEndDate_Month + ' * ' + scheduleStartDate_Year + '-' +  scheduleEndDate_Year;
                String jobID = system.schedule('Scheduled Fetch Events Daily Job', CRON_EXP, phca);
                ApexClass.events(webSite, selectedSiteName, stringColumns, date_from, date_to, token);
            }
            else if(mode == 'Weekly'){
                
            }
            else if(mode == 'Monthly'){
                
            }
        }
        catch(Exception e){
            
        }
    }
    // ====================================================== execute ==============================================================
    global static void execute(SchedulableContext sc){
        ApexClass phc = new ApexClass();
    }

This is based on this solution - Link 1 I'm trying to call the 'worker' method from the class that implements 'schedulable' and to @wire that to the LWC but it doesn't seem to work. Also, I'm building dynamic CRON expression so that the user has input on when to start and finish the execution.

My main question is - how can I make that method schedulable?

Thank you.

EDIT 1 - 10/27/2022

I have null for par1, par2 and par3 when the scheduled job executes. What might be the problem?

global with sharing class HttpCallout Implements Schedulable {
    public static String parameter1;
    public static String parameter2;
    public static String parameter3;

    public static void schedule(String par1, String par2, String par3){
        HttpCallout hc = new HttpCallout();
        parameter1 = par1;
        parameter2 = par2;
        parameter3 = par3;
        system.debug(par1);
        String CRON_EXP = '0 39 10 27 10 ?';
        String jobID = System.schedule('Scheduled Job', CRON_EXP, hc);
    }

    global static void execute(SchedulableContext sc){
        firstMethod(parameter1, parameter2, parameter3);  
    }
        @future(callout=true)
      global static void firstMethod(parameter1, parameter2, parameter3) {
        String str = HttpCall.getBearerKey(parameter1, parameter2, parameter3);
        system.debug(par1);
    }

1 Answer 1

2

You don't want to use @wire, as you're not allowed to make any permanent changes to the database in a wire method. This limitation is in place because these methods are cached on the client, so the actual Apex method might not be called every time when called repeatedly with the same parameters.

Instead, you have to call fetchEvents_schedule imperatively. To do this, call the method with the parameters:

fetchEvents_schedule({
  webSite: this.webSite,
  selectedSiteName: this.selectedSiteName,
  stringColumns: this.stringColumns,
  date_from: this.date_from,
  date_to: this.date_to,
  token: this.token,
  mode: this.mode,
  scheduleStartDate_Day: this.scheduleStartDate_Day,
  scheduleStartDate_Month: this.scheduleStartDate_Month,
  scheduleStartDate_Year: this.scheduleStartDate_Year,
  scheduleEndDate_Day: this.scheduleEndDate_Day,
  scheduleEndDate_Month: this.scheduleEndDate_Month,
  scheduleEndDate_Year: this.scheduleEndDate_Year,
  prefferedTime_Minutes: this.prefferedTime_Minutes,
  prefferedTime_Hour: this.prefferedTime_Hour,
}).then((result) => {
    // Do something here
});
5
  • Thank you for the answer. How should the schedule class look like? What should I put in the 'execution' part of the class?
    – Stojchesky
    Commented Oct 25, 2022 at 13:40
  • @Stojcheski Store the variables you need for the method in the class that has fetchEvents_schedule; you already have the basic structure set up; you can schedule the class with System.scheduleJob(jobName, cronString, this); Then, in the execute method, just call ApexClass.events, just as you would normally. You don't need to create a new PTEST, whatever that is.
    – sfdcfox
    Commented Oct 25, 2022 at 14:02
  • I've edited my question EDIT 1 - I get null values on par1, par2, par3. What might be the problem? I also added the schedulable class code.
    – Stojchesky
    Commented Oct 27, 2022 at 9:17
  • @Stojcheski Static variables aren't serialized, so make them instance properties public String parameter1, parameter2, parameter3;. Also, you don't need to new HttpCallout() in the schedule method, just: System.schedule('Scheduled Job', CRON_EXP, this);
    – sfdcfox
    Commented Oct 27, 2022 at 12:58
  • Thank you, that worked.
    – Stojchesky
    Commented Oct 28, 2022 at 6:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .