Search code examples
salesforceapex

It is necessary to perform the planned action through the apex scheduler


i have this code:

public static String currencyConverter() {
        
        allCurrency test = new allCurrency();
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        Http http = new Http();

        request.setEndpoint(endPoint);
        request.setMethod('GET');
        response = http.send(request);
        
        String JSONresponse = response.getBody();
        currencyJSON currencyJSON = (currencyJSON)JSON.deserialize(JSONresponse, currencyJSON.class); 
        test.USD = currencyJSON.rates.USD;
        test.CAD = currencyJSON.rates.CAD;
        test.EUR = currencyJSON.rates.EUR;
        test.GBP = currencyJSON.rates.GBP;

        Log__c logObject = new Log__c();
        logObject.Status_Code__c = String.valueOf(response.getStatusCode());
        logObject.Response_Body__c = response.getBody();
        
        insert logObject;

        if (response.getStatusCode() == 200) {
            Exchange_Rate__c ExchangeRateObject = new Exchange_Rate__c();
            ExchangeRateObject.CAD__c = currencyJSON.rates.CAD;
            ExchangeRateObject.EUR__c = currencyJSON.rates.EUR;
            ExchangeRateObject.GBP__c = currencyJSON.rates.GBP;
            ExchangeRateObject.USD__c = currencyJSON.rates.USD;
            ExchangeRateObject.Log__c = logObject.id;

            insert ExchangeRateObject;
        }
        return JSON.serialize(test);
    }

Here I am getting different currencies and then calling them in LWC and also I create two objects with values.

I want these objects to be created every day at 12PM.

Tell me how to implement this through the apex scheduler.


Solution

  • You need a class that implements Schedulable. Can be this class, just add that to the header and add execute method. Or can be separate class, doesn't matter much.

    https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm

    Something like

    public with sharing MyClass implements Schedulable{
       public static String currencyConverter() { ... your method here }
    
       public void execute(SchedulableContext sc) {
          currencyConverter(); 
       }
    }
    

    Once your class saves OK you should be able to schedule it from UI (Setup -> Apex Classes -> button) or with System.schedule 1-liner from Developer Console for example.

    Alternative would be to have a scheduled Flow - but that's bit more work with making your Apex callable from Flow.

    P.S. Don't name your variables test. Eventually some time later you may need "real" stuff like Test.isRunningTest() and that will be "fun". It's like writing

    Integer Account = 5; // happy debugging suckers