Using Sitecore Jobs

Sitecore contains a job system, allowing you to start and run jobs in the background. Jobs are perfect for long running operations. Scheduled tasks is jobs that is started at certain time.

Jobs have no HttpContext and, depending on how they are started, may run in a different context that you expect. For example, jobs started from the Scheuled tasks run in the “scheduler” context.

This is a madeup example on how to start a job that will traverse through Sitecore and do stuff to every item, starting from a certain root.

using System;
using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Jobs;
using Sitecore.Pipelines;
using Sitecore.SecurityModel;

namespace MyCode
{
  public class JobService
  {
    private string _JOBNAME = "MyJob";

    public Job Job
    {
      get { return JobManager.GetJob(_JOBNAME); }
    }

    public string StartJob(Item root)
    {
      JobOptions options = new JobOptions(_JOBNAME,
                                          "MyCode",
                                          Context.Site.Name,
                                          this,
                                          "ConvertData",
                                          new object[] {root});
      JobManager.Start(options);
      return _JOBNAME;
    }

    public void ConvertData(Item root)
    {
      ProcessAllItems(root);
      if (Job != null)
      {
        Job.Status.State = JobState.Finished;
      }
    }

    private void ProcessAllItems(Item item)
    {
      ProcessItem(item, pipeline);
      foreach (Item childItem in item.Children)
      {
        ProcessAllItems(childItem);
      }
    }

    private void ProcessItem(Item item)
    {
      if (Job != null)
      {
        Job.Status.Processed++;
        Job.Status.State = JobState.Running;
      }
      // Do something to my item
    }
  }
}

You can call the code like this:

JobService service = new JobService();
service.StartJob(Sitecore.Context.Item);

The job is created using the JobOptions class. This class create a Job with a job name and a category. The parameter “methodName” takes the name of a function to execute in the background. You include parameters using the last parameter.

When calling JobManager.Start() you execute the job in the background.

You can then use the Sitecore.Context.Job to get the current job for the current context. Or you can ask for a specific job (as I do in the “Job” property) using JobManager.GetJob().

A job have limited reporting capabilities, but you can use the Job.Status.Processed to indicate progress. You can even use the Job.Status.Total if you know beforehand how many operations the job is processing, and Sitecore Rocks will even convert the numbers displayed and show a percentage progress instead of a count. Use the Job.Status.State to indicate the status of your job (Initializing, Queued, Running, Finished).

Here is a simple example on how to check the status of a job:

protected void Page_Load(object sender, EventArgs e)
{
  JobService service = new JobService();
  if (service.Job != null)
  {
    Response.Write(string.Format("Job Status: {0}. Count: {1}", service.Job.Status.State, service.Job.Status.Processed));
  }
}

You can read more about jobs here:

Advertisement

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, Sitecore 6 and tagged , , . Bookmark the permalink.

10 Responses to Using Sitecore Jobs

  1. Lars nielsen says:

    Yup. I love the job manager, but unfortunately does not see it used even thought it is dead simple.

    You link to the Sitecore TaskManager. I dont know if it works for the latest Sitecore, but here’s a video of it: http://www.youtube.com/watch?v=p27pVB-JSJc

    Like

  2. Pingback: Migrating huge amounts of Sitecore content – Use the Sitecore Serializer | Brian Pedersen's Sitecore and .NET Blog

  3. Pingback: Basics of invoking Sitecore agent programmatically « Sitecore basics!

  4. Pingback: How Sitecore PowerShell got GUI support… a tale of JobMonitor and Sitecore async UI API. | Codality

  5. Pingback: Sitecore Job Viewer – see what Sitecore is doing behind your back | Brian Pedersen's Sitecore and .NET Blog

  6. Bryan P says:

    Hi Brian, is it possible that Sitecore 8 completely broke this feature? I cannot get it to work at all, using working code that came straight out of a Sitecore 7.2 project. I *always* get the same error: Could not resolve method: on object of type: . I’ve tried changing the name of the method, changing protection level, moving the method to another object, rebuilding the assembly from scratch, etc. etc. Nothing is working here, with code that was easily dropped into a Sitecore 7.2 instance and worked like a charm. Any ideas?

    Like

  7. Bryan P says:

    OK, I figured it out. Dumb mistake. Passing a non-empty parameter array changes the signature of the method that Reflection will be looking for. Would be nice if .NET would would tell you exactly which method it was failing to find, since this error will always be ambiguous in an environment allowing overloading.

    Like

  8. Pingback: Sitecore remove “Job started” and “Job ended” from log files | Brian Pedersen's Sitecore and .NET Blog

  9. Pingback: Which of my old Sitecore posts are still valid in Sitecore 9? | Brian Pedersen's Sitecore and .NET Blog

  10. Pingback: Sitecore The type or namespace name ‘Job’ does not exist in the namespace ‘Sitecore.Jobs’ (are you missing an assembly reference?) | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.