+ Start a Discussion
OpsterOpster 

Scheduled Apex Class DML Inserts multiple tasks - How can I set the CreatedBy ID???

I have a Scheduled Apex Class that runs nightly.  It loops through a bunch of data and creates a Task for some users.   I would like these tasks to be CreatedBy the Owner of the Objects I am looping through.   I was going to use System.runas() but since I do a batch insert I am not sure this will work.  They would all end up being Created By the one user I am impersonating. 

 

I could group the tasks and use System.runas() for each group of tasks who the Created By field should be set to, but I was wondering if there is a better way.

 

So how can I insert a bunch of tasks Created By different users and not the user the Apex Class is running as?

bob_buzzardbob_buzzard
Unfortunately you can only use runAs in test methods according to the docs, so I think you may well be out of luck.
AhmedPotAhmedPot

On similar lines. I have another doubt.

 

If my test criteria is records created 10 days back. and my query returns those records created 10 days back and do some processing. So how do we create records in test class which are created 10 days back. can we stamp created date field in test classes?

bob_buzzardbob_buzzard

Not as far as I'm aware - I've tried that sort of thing in the past without success.  I always get the error message that the field is not writeable.  I believe you can ask salesforce for a feature activation that allows you to write to this field, but its intended as a short term measure while you migrate data, not as a long term solution.

 

Looking back, I've tended to add my own datetime field to records that need to be handled in this way.