January 27, 2011

Use the sitecore jobs

When you need to do some long running operations in the Sitecore backend (like an import form example) most of the time we do that as we do for the small tasks.

But this is not a very good practice because the task is synchronous in the main thread and the admin is freeze until the task is finished.

In sitecore they are a very simple way to execute these tasks in another thread: the jobs.

Here is a small code snippet to create a job :
//Create the options and pass some attributes
JobOptions options2 = new JobOptions("The job name", "The job category", "MyWebsiteName", MyObjectInstanceThanContainTheMethodToExecute, "The Method Name To Exectute", new object[] { parameter1ForTheMethod, parameter2ForTheMethod });
options2.ContextUser = Context.User;
//This line allow to keep the job alive at least the time needed to check the lastest infos for the status.
options2.AfterLife = TimeSpan.FromMilliseconds((double)(POOLING_INTERVAL * 2));
//The thread priority
options2.Priority = System.Threading.ThreadPriority.Normal;
//Start the job himself
Job job = JobManager.Start(options2);
job.Options.CustomData = status; //Status is a object shared between my job and this class (to check the status of the import)
//Keep an instance of the if you need to check his status
this.JobHandle = job.Handle.ToString();

You may also launch a timer to check the status (how many items are already imported for example) but I will create another subject about “How to create a admin wizard”

1 comment: