+ Start a Discussion
RJ12RJ12 

Execute Workflow Actions using Batch Apex.

I have a 'Task' and 'Email Alert' workflow actions. Is there a way to execute those workflow actions using Batch Apex?

Can anyone help me out on this?

NagendraNagendra (Salesforce Developers) 
Hi RJ,

Below is the working example of the above requirement.

Use Case:

I have a workflow that needs to be run daily to check is the status of a particular file is completed or not. If the file is not completed then the workflow should be triggered and an Email alert should be sent to the user.

I checked if the above scenario could be accomplished in a workflow alone, but it was not possible. So I thought a scheduled Apex class could be used. But the problem now is can a workflow be triggered by an Apex class? If so can someone please tell me how?

Resolution:

Yes, workflow rules can be triggered from a scheduled/batched class, but you may as well just send the email directly through Apex Code-- you'll save the possibility of validation rules, etc possibly preventing the email from sending. Also, you'll have to actually update the record, which will affect the Last Modified By/Date fields, which may not be your intent.

Triggering the workflow is as simple as making a qualifying update to the record(s) that should be triggered. You could even just update all records everywhere and let whatever happens to happen, but that'd be a poor practice for large datasets.

An example scheduler might look like:
public class TriggerUpdates implements Database.Batchable<SObject>, Schedulable {
    public void execute(SchedulableContext sc) {
        Database.executeBatch(this);
    }
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([SELECT ... FROM ... WHERE ...]);
    }
    public void execute(Database.BatchableContext bc, SObject[] records) {
        Database.update(records, false); // allow partial success
    }
    public void finish(Database.BatchableContext bc) 
        // Nothing to do
    }
}
This works simply because workflows evaluate each time a DML occurs, even if no fields were actually modified. The only change that needs to be made to the above code is to add to the query.

Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra