Skip to content
September 16, 2014 / kiranpatils

Do you know why you check Async Checkbox while configuring Scheduled Task?

Challenge:

Howdy Folks, Your friend is back to share his learnings with you.

I hope you enjoyed my earlier post Scheduled Task Basics and If you haven’t read it. I would strongly recommend you to read. If you are playing around/going to play around with Sitecore Scheduled Tasks. Read?! Good!

We were making sure all our schedule tasks are working fine or not. While doing that check we found that few scheduled tasks has been configured as “Async” and few are not. Those who are visual [So, as I] here’s what we are talking about:

2014-09-15 22_39_14-Sitecore

You have seen that check-box earlier? Checked for few Scheduled Tasks and NOT checked for few? Why??!

Just a note : We follow one formula to understand anything from basics and that formula is “W-W-H” it stands for What-Why-How. You take anything in life and apply this formula, it will work! (It works at-least for us! we hope it will work for you as well!)

You also had this question? And as you were approaching a strict deadline, you thought I will check later on. And then later never came! [Actually, It never comes!]. So, We started a discussion. Whether we should keep this ON or not. That’s How we work at Horizontal Integration (HI). Because THIS IS OUR DOMAIN

THIS IS OUR DOMAIN

THIS IS OUR DOMAIN

We ask questions a lot!, and because of excellent people around. We are able to find out the answers!

And the search started . In the whole Globe we found only one article which mentioned about Async checkbox, And NOT Surprisingly it was from John West : http://www.sitecore.net/Learn/Blogs/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/All-About-Sitecore-Scheduling-Agents-and-Tasks.aspx

But unfortunately we haven’t found “WHY”. So, we started discussing what do they mean by “Async” It means execute my Schedule Task Async. But isn’t it the Basic fundamental of Scheduled Task. Don’t they get executed asynchronously on backed thread. Rather than Main Thread? Same thoughts?! That’s why we work on Sitecore! 🙂

Any other thoughts, You can think of? No? Eager to know the “WHY”. Let’s go!

Solution:

Then we thought to talk to our best friend Reflector [Yours too?! – See, we got a common friend! :)] and we found following  things:

Here’s How your Scheduled Task gets executed:

  • Sitecore.Tasks.DatabaseAgent tasks gets executed for each Database at defined interval:
 <!-- Time between checking for scheduled tasks waiting to execute -->
      <frequency>00:01:00</frequency>
      <!-- Agent to process schedules embedded as items in a database -->
      <agent type="Sitecore.Tasks.DatabaseAgent" method="Run" interval="00:10:00">
        <param desc="database">core</param>
        <param desc="schedule root">/sitecore/system/tasks/schedules</param>
        <LogActivity>true</LogActivity>
      </agent>
      <!-- Agent to process schedules embedded as items in a database -->
      <agent type="Sitecore.Tasks.DatabaseAgent" method="Run" interval="00:01:00">
        <param desc="database">master</param>
        <param desc="schedule root">/sitecore/system/tasks/schedules</param>
        <LogActivity>true</LogActivity>
      </agent>
      <!-- Agent to retrieve a URL -->
      <agent type="Sitecore.Tasks.UrlAgent" method="Run" interval="00:15:00">
        <param desc="url">/sitecore/service/keepalive.aspx</param>
        <LogActivity>true</LogActivity>
      </agent>
  • It will pick your scheduled tasks from particular database’s /sitecore/system/tasks/schedules path
  • And checks whether this task is due to run or not. By checking Last run and Schedule field

Clear?! Now, Let’s see how it gets handled at Code Level:

  • Sitecore.Tasks.DatabaseAgent.Run Method iterates through all scheduled items and calls Execute Method if Item IsDue
 foreach (ScheduleItem item in schedules)
        {
            try
            {
                if (item.IsDue)
                {
                    this.LogInfo(&quot;Starting: &quot; + item.Name + (item.Asynchronous ? &quot; (asynchronously)&quot; : string.Empty));
                    item.Execute();
                    this.LogInfo(&quot;Ended: &quot; + item.Name);
                }
                else
                {
                    this.LogInfo(&quot;Not due: &quot; + item.Name);
                }
                if (item.AutoRemove &amp;&amp; item.Expired)
                {
                    this.LogInfo(&quot;Schedule is expired. Auto removing schedule item: &quot; + item.Name);
                    item.Remove();
                }
            }
            catch
            {
            }
            if (this.IsValidJob(job))
            {
                JobStatus status = job.Status;
                status.Processed += 1L;
            }
}
  • Sitecore.Tasks.ScheduleItem.Execute() Method checks whether Schedule Task is Asynchronous [Our “Async” Checkbox!]or not? Based on it calls either ExecuteAsynchronously or ExecuteSynchronously method.
public void Execute()
{
    try
    {
        CommandItem commandItem = this.CommandItem;
        if (commandItem != null)
        {
            if (this.Asynchronous)
            {
                this.ExecuteAsynchronously(commandItem);
            }
            else
            {
                this.ExecuteSynchronously(commandItem);
            }
            this.LastRun = DateTime.Now;
            if (this.IsCompleted &amp;&amp; this.AutoRemove)
            {
                Log.Info(&quot;Schedule is completed. Auto removing schedule item: &quot; + base.Name, this);
                base.InnerItem.Delete();
            }
        }
    }
    catch (Exception exception)
    {
        Log.Error(&quot;Error executing schedule item: &quot; + base.Name, exception, this);
        throw;
    }
}
  • This is what written inside ExecuteAsynchronously method – Start a Job!
  private void ExecuteAsynchronously(CommandItem command)
{
    JobOptions options = new JobOptions(this.GetJobName(command), &quot;scheduling&quot;, &quot;scheduler&quot;, command, &quot;Execute&quot;, new object[] { this.Items, this }) {
        AtomicExecution = true
    };
    JobManager.Start(options);
}
  • This is what written inside ExecuteSynchronously method — Which calls command.Execute method, which directly calls provided Command Method using ReflectionUtil classes:
private void ExecuteSynchronously(CommandItem command)
{
    command.Execute(this.Items, this);
}

Things are getting clear?! It means that when you keep your scheduled tasks as ASYNC [Check the Checkbox]. Then they all will be getting executed at same time. Without waiting for the last one to complete. e.g. if you’ve two scheduled tasks A and B and they both run after every 2 Hours and they both take roughly 5 minutes to complete their own task. And let’s see how they gets executed. Consider currently it’s 12:02 and they both are due to run:

  1. ASYNCCHECKBOX is Checked:
    1. They both will get executed at same time e.g. 12:02
  2. ASYNCCHEKBOX is Un-Checked:
    1. Task-A will start at 12:02 and it will get completed at 12:07
    2. Task-B will start at 12:07 and it will get completed at 12:12

But all this is theory. How can we prove that? I know you are an engineer, to who E=MC2 also needs to be proved! 🙂 Let me try to prove it!

  • Take1 : With Async checkbox unchecked [Click Image for full view]:

Async-Scheduled-Task-Settings

  • Here’s what we got from Log files:

ManagedPoolThread #16 00:31:53 INFO  Starting: Schedule-Task-A
ManagedPoolThread #16 00:31:53 INFO  MyTaskA Started : 9/16/2014 12:31:53 AM
ManagedPoolThread #16 00:32:23 INFO  MyTaskA Completed : 9/16/2014 12:32:23 AM
ManagedPoolThread #16 00:32:24 INFO  Ended: Schedule-Task-A
ManagedPoolThread #16 00:32:24 INFO  Starting: Schedule-Task-B
ManagedPoolThread #16 00:32:24 INFO  MyTaskB Started : 9/16/2014 12:32:24 AM

Total Time :

  • Take2 : With Async checkbox checked [Click Image for full view]:

Async-Scheduled-Task-Settings-Take2

  • Here’s what we got from Log files:

ManagedPoolThread #2 00:52:38 INFO  Starting: Schedule-Task-A (asynchronously)
ManagedPoolThread #3 00:52:38 INFO  Job started: ScheduleCommand ‘{E8F323D2-3FD6-4CE1-B4B0-7F184ECB89AC}’
ManagedPoolThread #3 00:52:38 INFO  MyTaskA Started : 9/16/2014 12:52:38 AM
ManagedPoolThread #2 00:52:40 INFO  Ended: Schedule-Task-A
ManagedPoolThread #2 00:52:40 INFO  Starting: Schedule-Task-B (asynchronously)
ManagedPoolThread #4 00:52:40 INFO  Job started: ScheduleCommand ‘{4544474E-A0E2-4794-A9C2-BBE1D194301B}’
ManagedPoolThread #4 00:52:40 INFO  MyTaskB Started : 9/16/2014 12:52:40 AM
ManagedPoolThread #2 00:52:40 INFO  Ended: Schedule-Task-B

In Summary, This “Async” Check box. Sitecore meant to say — Sir/Madam, Would you like to execute your Task Asynchronously? So, other tasks don’t have to wait for your task to get completed!

What’s the Best Practice? : My suggestion would to keep Async checkbox checked for all tasks [Or for long running tasks], Until and unless your one task is dependent on the later on! Which I can’t think of will ever be the case — Can it be?! Happy to be corrected!

Till Then, Happy Sitecoring! 🙂

Thanks to My colleague Marcia — Who brought this topic for brainstorming!

Good Reads:

http://briancaos.wordpress.com/2011/06/28/run-sitecore-scheduled-task-at-the-same-time-every-day/

Advertisements

3 Comments

Leave a Comment
  1. Abhishek S / Dec 5 2015 2:32 am

    Outstanding explanation. Thank you.

  2. Pratik W / Feb 21 2017 5:04 pm

    Thank you for the information !

Trackbacks

  1. One more way to Run Sitecore scheduled task at the same time every day | Sitecore basics!

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: