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
GsajeeshGsajeesh 

Specify the 'Run As ' user while Scheduling an Apex job

Hi,

 

Is there a way in Salesforce to specify the running user while scheduling and apex job?

I have an Apex Batch job which auto creates deals based on some criteria and posts chatter messages. The Batch job has to be scheduled for once a day.

I am able to schedule it using the 'Shedule Apex' button.
 But in this case , since the scheduler is me, the message of activity completion comes to me and the chatter posts mention my name in the posts .

I need a way to schedule the batch job as a generic system user so that the messages go to generic email id and the chatter posts mention generic user name.

 

Please help

 

Thanks

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You could log in as the generic system user (assuming you have a license assigned to it, is active, with sufficient permissions, etc) and schedule it there. The only downside is that the user has to remain active, although I know many clients have a generic user for administration purposes anyways (e.g. integrations, default workflow messages, etc), so if you already have this user set up, it's just one more thing you could add to it.

All Answers

bob_buzzardbob_buzzard

Not easily.  You can only use the System.RunAs() method when in unit tests, unfortunately.

 

The one way that you can switch the user is to fire an email to an inbound email handler service, as you can specify the context user that the service code runs as, and schedule the class when the email is received.  Its far from an elegant and robust solution, but as far as I'm aware its the only way.

sfdcfoxsfdcfox

You could log in as the generic system user (assuming you have a license assigned to it, is active, with sufficient permissions, etc) and schedule it there. The only downside is that the user has to remain active, although I know many clients have a generic user for administration purposes anyways (e.g. integrations, default workflow messages, etc), so if you already have this user set up, it's just one more thing you could add to it.

This was selected as the best answer
GsajeeshGsajeesh

Thanks Bob and sfdcfox...