function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to find out if code is running from time-based workflow?

I have a code that calls Auth.SessionManagement.getCurrentSession()
Session is not available in asynchronous processes and the code throws 
unexpected exception that can't  be caught.

System.UnexpectedException: Current session unavailable Class.Auth.SessionManagement.getCurrentSession:

I can preven't the code from this situation by checking the execution context. (System.isBatch(), isFuture ect)But I'm having problems because of time-based workflow that executes field updates and runs the trigger. The system.isScheduled() detects only scheduled apex. Is there a way to prevent my code from running into the check and throwing an exception?
SwethaSwetha (Salesforce Developers) 
HI Monika,

I don't think there is a direct way to identify time-based workflow execution.You might want to use a custom setting or custom metadata type to store a flag that indicates whether the code is running from a time-based workflow. You can set this flag in the time-based workflow action using a field update, and then check the flag in your code to determine if it is running from a time-based workflow.

For example, you can create a custom setting called "TimeBasedWorkflowFlag__c" with a single checkbox field called "IsRunningFromTimeBasedWorkflow__c".

In your time-based workflow action, you can add a field update to set the "IsRunningFromTimeBasedWorkflow__c" checkbox to true. Then, in your code, you can check the value of this checkbox to determine if the code is running from a time-based workflow.
Boolean isRunningFromTimeBasedWorkflow = false;
TimeBasedWorkflowFlag__c flag = TimeBasedWorkflowFlag__c.getInstance();
if (flag != null && flag.IsRunningFromTimeBasedWorkflow__c) {
    isRunningFromTimeBasedWorkflow = true;