How to get UserInfo.getSessionId() in Scheduler/Batch

I am building sfdc application that required me to call and do add/update using Http method at vendor application in external server daily. They created one account for me in their application.
In order to proceed with data manipulation at their application, I need to retrieve the token by passing my session id using UserInfo.getSessionId().

After retrieved the token, then I am able to do other process.The issue is, when I run my code in Apex Execute I am able to retrieve UserInfo.getSessionId(), but when I put in Schedule and run it ,the session Id return null.

global class Test_Sched  implements Schedulable{
global void execute(SchedulableContext sc) {

    System.debug('Test ' + UserInfo.getSessionId());  //This returning null

    String sessionId=UserInfo.getSessionId();
   //pass the session id to the class that call http and process the data in external apps
staticclassprocess(sessionId)   ;      
}
}

I read the documentation here When do Sessions expire? but still not able to understand how to pass the sessionId from scheduler.

Answer

Pass it in as the initial state, this will mean you have to schedule it in code though. So, your class:

global class Test_Sched  implements Schedulable{
    private String sessionId;

    global Test_Sched( String sessionId ) {
        this.sessionId = sessionId;
    }

    global void execute(SchedulableContext sc) {

        //pass the session id to the class that call http and process the data in external apps
        staticclassprocess(sessionId)   ;      
    }
}

And to schedule it:

System.schedule('Test_Sched', '0 0 1-23 * * ?', new Test_Sched(UserInfo.getSessionId()));

Take heed of the advice/warnings in the post When do Sessions expire?.

I think this works because when you schedule a job, it is serialized with its initial state and then deserialized for use at the scheduled point. Beware of your sessions expiring too (we have found that if you close your browser, its fine but if you ‘logoff’ from SF then your session will expire immediately).

Attribution
Source : Link , Question Author : unidha , Answer Author : Community

Leave a Comment