Scheduled tasks in EPiServer are a great way to automate things on your website and work really well for things like clearing down dead baskets in online stores, sending user updates and reminder etc.
But what happens when you want something to be scheduled that you do not want to run every 10 minutes or 4 hours of every day? The default implementation of the scheduler is that you pick a repeating period that you want to apply to your scheduled task and that will be religiously adhered to.
My trouble is, I want to do something in my current project that runs at three set times on weekdays only. This got me wondering as to what the best way was to do this.
My solution was to reassess when the task should next run every time it is executed. Say for simplicities sake that I want the task to run at 09:00 and 16:30 every weekday. The first time that the task runs it take a look at the times I specified in the configuration file (web.config) and looks for the next time it can run. We do a simple date comparison and then reset the next scheduled run date to the resulting value.
The ins and out of how I;m doing this are unimportant at this stage, suffice to say that the code needed to alter the next scheduled is detailed below. Here what we do is simply tell the task to run five minutes form now:
string plugInId = ConfigurationManager.AppSettings["ScheduledPlugInID"];
PlugInDescriptor desc = PlugInDescriptor.Load(int.Parse(plugInId));
ScheduledPlugInAttribute attr = desc.GetAttribute(typeof(ScheduledPlugInAttribute)) as ScheduledPlugInAttribute;
ScheduledJob job = ScheduledJob.Load("Execute", desc.TypeName, desc.AssemblyName);
job.NextExecution = DateTime.Now.AddMinutes(5);
job.Save();
Note that I’m pulling the plug-in ID from the web.config in order to achieve this. I could not find a more glamorous way to do this in the short amount of time that I had, though any feedback is clearly welcome.
I like to make this the first port of call in the Execute() method of my scheduled task simply because the time the task takes to run then no longer impacts the next run date of the task.
Make sure that in the admin section, you set the interval time in the admin screen (above) to as short a period as you dare. If the interval period is more than the time span to the next period, then is seams not to work. I just set it to one minute for this example and everything worked fine.

No Comments »
No comments yet.
RSS feed for comments on this post. TrackBack URL
Leave a comment