Sitecore – Task Schedulers

This is a 3 part post, where we will be creating a Sitecore Task Scheduler to read RSS Feed and create item in the sitecore item and finally, sort the created items using a custom Publish Date field.

Part 1 – Sitecore Task Scheduler

Sitecore has a build in Task Scheduling Agent that schedules predefined/build in tasks at the specified intervals.

Before discussing about more about this concepts or features I would like cite you how it can be put in to use.

Suppose you need a logic that needs to run at a specific time in a specific interval (Like a routine) like cleaning a database, posting contents to Web API or Sending a report  etc, Sitecore Task Scheduler are to the rescue.

Let’s look on how we can read a RSS Feed at a specific interval daily and create Items in Sitecore Content Tree and publish them using a Custom Task Scheduler which can then be presented in the website based on the UI.

For every Task Scheduler to be created an Run, we need three components.

  1. Command — This is the Logic(the code) that needs to be executed every time when the scheduler schedules the TASK
  2. Items – This is the item that will be passed as an Argument to the logic and our operations can be carried out in this item.(Item can be subjected to CRUD)
  3. Schedulers — This has the data on when a command needs to be called, at what time interval and has the data on when it’s Last Run.

All these components can be found under – /sitecore/system/Tasks — It is recommended to cerate Custom Tasks under this content so that it will be easy to manage.

Settings 
Tasks 
Commands 
Content Testing 
Email Campaign 
Guardian 
@ PowerShell Script Command 
Schedules 
_ Task Schedule 
Content Testing 
Guardian 
SyncRSSFeed 
Quick Info 
Item ID: 
Item name: 
Item path: 
Template: 
Created from: 
Item owner: 
Advanced 
(EF58CA2C-3E5944EO-82C1-97+9898535F} 
Tasks 
/sitecore/system/Tasks 
- {239F9CF4-E5AO-44EO-B342-OF32CD4C6D88) 
(unknown)

Command: Create a custom command under /sitecore/system/Tasks/Commands/Your Project/Command using the system command template – /sitecore/templates/System/Tasks/Command

  • The created item will have two fields – Type and Method.
    • Type  – refers to your Namespace with Class Name and Assembly in should be provided in the format (MySitecore.Features.NewsFeed.Tasks.SyncRSSFeed,MySitecore.Features.NewsFeed)
    • Method – the method name in your class to which the control will be passed.
Marketing Control Panel 
Modules 
Publishirg targets 
Settings 
€ Tasks 
Commands 
Content Testing 
Email Campaign 
Guardian 
syncRssæed 
@ PowerShell Script Commanc 
Schedules 
_Task Schedule 
Content Testing 
Guardian 
syncRSSFeed 
Toolbox 
Workflows 
Templates 
Ük Info 
Item ID: 
Item name: 
Item path: 
Template: 
Created from: 
Item owner. 
Type (shared): 
syncRSFeed 
'sitecore/templatesßystem/Tasks/Con-,mand - (58119A3E-560E-4DA6-97C6-1ACE8ASB1219) 
(unknown) 
sitecore\Admin 
MySitecore. Features. Newspeed.Tasks.SyncRSSPeed, MySitecore.Features.NewsPeed 
Method (shared]:

Scheduler: Create a Custom Scheduler Item under /sitecore/system/Tasks/Schedules/Your Project/Scheduler using the system Scheduler template – /sitecore/templates/System/Tasks/Schedule

  • The Schedule Item has the following key fields
    • Command – It’s of DropTree type with the Command Folder as it’s source. You can select the command item created from the DropDown
    • Items – Map the Item that needs to be passed to the custom logic
    • Schedule –  The Interval in which the task needs to be run it should be specified in the following format –

{start timestamp} | {end timestamp} | {days to run bit pattern} |{interval}

Start/End Timestamp Format – YYYYMMDD in this example it’s 20190816 and I don’t have an end date so I have set to the maximum – 99990101

  • The Day are set in bit pattern. With a bit value for each day of the week.
    • Sunday – 1
    • Monday – 2
    • Tuesday – 4
    • Wednesday – 8
    • Thursday – 16
    • Friday – 32
    • Saturday – 64
  • So if mention the sum of the days for which the tasks needs to be run for example, if it needs to be run every Monday set the value to 2. If it needs to be run every Monday and Tuesday (2+4) set the value to be 6
  • If it needs to be run everyday – sum of all the days – 127 would be the value. In this example I have set it to 127
  • Interval = HH:MM:SS 01:00:00 means the task will run every one hour. 00:02:00 means the task will run every 2 minutes.
  • Last run –  Indicates the value to last run date/time
Item 
Mosie Libryy 
System 
AliaÆ 
Cist Manager 
Merketing 
targets 
Semngs 
Commenas 
Content Testing 
Email Campaign 
a Gurdizn 
syncRSSFed 
Scneøules 
_%sk Scnzule 
a •U Gutrdian 
S syncRSSFeed 
templates 
'Syste m kS'SChed u es/G rd i' 'Sy SS Feed 
Com.' 
[snare'): 
201908161999901011127 loom. 
Last nun (snared]: 
'0:32 AM

Part – 2  Read RSS Feed and Create Items based on RSS Item template programmatically.

Now to the Custom Class (Mentioned in the Command Item – Type field). You can check creating the Sitecore command/schedule items and creating the class with Execute method and specifying it’s information to the created Sitecore item. To check simply put in a log and check the log file whether the log text is present.

us ing 
us Ing 
us ing 
tecore. Data. ; 
Sys tem; 
System. Col lections. Generic ; 
System. L inq; 
System. Text; 
System. Threading . Tasks ; 
mySitecore. Featur•es . Neus Feed . Recxjsitor•y ; 
mySitecore. Features . Newsfeed. %dels; 
namespace Mitecore.Features. Newsfeed. Tasks 
class SyncRSSFeed 
public void itans, Sitecore.Tasks.ConmandIter1 gprnand, Sitecore.Tasks . Scheduleltem yghedule) 
Log. Sitecore scheduled task is run! % this)' 
IRSSFeedRep05itory _rep05itory - new HSSFeedRep05itory(); 
foreach (Item item in items) 
foreach (Item RSSFeedItem in item. Children) 
string url — RSSFeedItem. 
RSSItemList = _ repository.ReadRSSFeed(urI); 
_repository. DeleteRsssub1tems(RSSFeed1te.) ; 
_revx»sitory. CreateRSSItem( RSSItenList RSSFeedIt—) 
_ repos itory. Publi5 hRSSItem(RSSF eedltem) ;

We will work on the logic for reading the RSS Feed and creating Items in Sitecore based on the RSS Item Template. I have created a RSSItem in Sitecore with the following fields.

RSSItem

Content 
Foundation 
List Manager 
Modules 
Project 
System 
to Sample 
user Defined 
MySitecore 
Feature 
'O contact 
Meta Data 
Navigation 
'O Page Contents 
'0 Profile 
Rss 
El Rss;eed 
RSS Item 
SEO 
Foundation 
Inheritance 
Rss Item 
Title 
Link 
Description 
Source 
Single-Line Text 
Single-Line Text 
Single-Line Text 
Single-Line Text 
Rich Text 
Datetime

RSS Feed:

Modules 
Project 
System 
Sample 
user Defined 
MySitecore 
Featu re 
Contact 
MetaData 
Navigation 
Page Contents 
Profile 
RSS 
RSSFeed 
RSS Item 
RSS Feed 
Title 
Source 
Add a new field 
Add a new section 
Single-Line Text 
Single-Line Text 
Single-Line Text

The idea is to have a Folder Item (RSS) that will be passed as an input to the Task Scheduler. This RSS Folder will have sub items of type RSS Feed. The RSS Feed  has two fields – Name and the Feed URL. Based on the feed URL, RSS Item will be created as a sub item under the corresponding RSS Feed.

In a nutshell, the final folder will be something  like

RSS 
Business 
International 
National 
sports 
Cristiano Ronaldo bags hattrick closes on goa 
Harry Kane treble as England demolish Monteneg 
World Cup Qualifiers Injurytime goal saves India 
Ajzaw1Bagan opener on Nov 30 
Khongsai strikes MEGS winner 
Man Citys Bernardo Silva banned by over twee 
Footballer David Villa to retire at end Of season 
Mark 2 
Media Library 
Item ID: 
Item nanE: 
Item path: 
Template: 
Created from: 
Item owner: 
{26EEIF0%80SC49SD41ED-688B19DZD82) 
/sitecore/content/Mark 1 'Guardianßhared Content/RSS/Sports 
/sitecore/tempIatesJMySitecore/Feature/Rssnss Feed (A9668C48-FACC48F681 F2-SCS4411 C71FE} 
tun known] 
sitecoreudmin 
Pootball Newspeed 
Source: 
httpswwwwthehindu.com/spoffootballffeeder/detault.rss
NSViS8tion 
RSS 
Intematior.• 
Crista m bags nattrick on 1 OO go i 
England 
World Cup Qualifiers Lnjur•ytime go-al India 
on Nov 30 
strike MEGS winner 
Man 
etc ot 
Wyse 
Media Libmry 
Common 
Found 
List V a neger 
Cri%iano closes on 
https://m.thehindu 100-80' IS - 
SuSE*St 
Edit HTML 
Ronaldo has 98 goals and could become only the second player to score a century his country ate' Iran's Ali Daei

Now we will add logic to read RSS Feed and Create RSS Item in Sitecore whenever this Task is RUN.

IRSSFeedRepository.cs 
RSS Feed Repositorycs 
SyncRSSFeed.cs 
_FeaturedArticles.cshtml 
MySitecore.Features.t•. 
g Newsfeed 
sing 
using 
using 
using 
using 
using 
MySitecore. Features. NewsFeed . *'dels • 
Si tecore. Data. It&s ; 
Sy sten ; 
Sy St COL . c ; 
System . L inq; 
Sy sten . Text ; 
System . Threading. Tasks; 
System. XmI. Ling; 
E namespace 
interface IRSSFeedRem»sitory 
ReadRSSFeed(string url); 
2 references 
void RSSItemList.Item Parentlte•) ; 
string Title); 
void DeleteRSSSubItems(Iten Parentltem); 
void PublishRSS1tem(1tem RSSFeed1te.);
catch (Sy5temException Ex) 
Sitecor•e.Diagnostics. create it— 
RSSSitecoreIt&. Editing. CancelEdit() ; 
else 
is returned as in 
catch (SystemException SysEx) 
at + 
this) s 
- createRSS1tem", 
this); 
this);
public void DeleteRsssub1tems(1tem Parentlte.) 
if (Parentltem. HasChiIdren) 
int output — Parentltem. DeleteChiIdren(); 
public void PublishRSSItem(Item RSSFeedItem) 
if (RSSFeedItem null) 
publishoptions = PublishOptions(RSSFeedIten.Database, 
publishevtions.RootItem = RSSFeedItem; 
true; // Publish Sub Items 
publi5hoption5.PubIi5hReIatedIt&5 — false; 
publishoptions.CompareRevisions - false; 
var handle — Publishmanager.publish(ne'.' PublishOptions[] { publishoptions 
bool publishAsync — false; 
if (publisMsync) 
return ; 
Publ i st-manager. NaitFor(handIe) ; 
Database. GetDatabase( "web" ) 
Publist%de. Smart , 
RSSFeedI tea. Language , 
DateT Ime. Nou) ;
public urI) 
WebCIient "client — new WebCIient(); 
string RSSData — 
XDocument xml — XDocment . Parse (RSSData); 
var RSSFeedData = (from x in xml . 
Title — ((string)x. 
Author = 
Category = 
Link = 
Ikscription - ((strine)x. 
PuM)ate — ( (DateTime)x. E-leænt( "pubDate")) 
return 
public string Title) 
return Regex.RepIace(TitIe, "

Part – 3 Custom Sort – Based on the PubDate field

Sitecore generally sorts sub items based on the item name. It can also be sorted based on other parameters like Created, Updated, Reverse etc all these are OOTB.

After reading the Feed and creating the RSS Items under RSS Feed, the created items will be sorted by the RSS Item Name. While setting this as a data source to a rendering the latest RSS Item from the RSS Feed wont be displayed as sub items are sorted based on their title.

But while displaying the feed in our website, it would be useful only if the latest items are displayed first. In order to achieve this, we will creating a Custom Sort Approach based on the Published Date by extending the system comparer class.

To Create a custom sort, we need to create a class that extends Sitecore.Data.Comparers.ExtractedKeysComparer.

And we can add our logic by overriding the following three methods, DoCompare,ExtractKey and CompareKeys

DoCompare compares the items based on the field name and returns the sorted item list.

Extract Key Returns the key object (the item and the key-Published Date field value)

Based on the keys, the items will be compared in CompareKeys method.

an amp space Sort 
public class PubDateSort : ExtractedKeysCæparer 
static string DateFieId — -PubDate"; 
protected override int iteml, Item it&2) 
DateTIme datel = GetDateTime(itemI); 
DateTime date2 — GetDateTime(item2); 
return 
private DateTi— GetDateTime(Item it&) 
return 
public override IKey ExtractKey(Item item) 
return (IKey)new KeyObj() 
Key = (object 
DateTime.ninVa1ue); 
protected override int keyl, IKey key2) 
return ( (DateTime)key2.Key) (DateTime)keyI.Key);

Now create a Child Sorting Item named Publish Date under /sitecore/system/Settings/Subitems Sorting and update the Type – Class, Assembly

Rules 
Security 
Services 
Simulators 
Subitems Sorting 
Created 
Default 
Display name 
Logical 
Published Date 
Reverse 
Updated 
Validation Rules 
Workflow 
Tasks 
Tnolhnx 
Quick Info 
Item ID: 
Item name: 
Item path: 
Te m plate: 
Created from: 
Item owner: 
Published Date 
/sitecore/system/Settings/Subitems Sorting/Published Date 
/sitecore/templatesJSystem/ChiId sorting - (FOCBFD8C-D5EF-43E1-A4D7ÆB386C77B9E4) 
[u n k nown] 
sitecore\uAdmin 
Type - Class*ssernbly, e.g. MyNamespace.MyType,MyAssembly.dll [shared): 
MySitecore. Featu res.NewsFeed.Sort. PubDateSOrt,MySitecore.Features.N ewsFeed

Now the created Child Item Sorting will be listed in the Sub Item sorting option.

NAVIGATE 
REVIEW 
ANALYZE 
PUBLISH 
VERSIONS 
Content 
Quick Info 
Item ID: 
Item name: 
Item path: 
Template: 
Created 
Item owner: 
Type - Clas 
MySitecore. 
Sort Order of Subitems 
Select the criteria for how the subitems must be sorted. 
x 
C) Insert from template (1 of 1) 
Navigation 
Business 
International 
National 
Sports 
Cristiano Ronaldo bags hattrick closes or 
Harry Kane treble as England demolish N 
World Cup Qualifiers Injury-time goal sav 
Aizawlaagan opener on Nov 30 
Khongsai strikes MEGs winner 
Man CityS Bernardo Silva banned by FAC 
Footballer David Villa to retire at end of 
Sorting: 
Published Date 
Cristiano Ronaldo bags hattrick closes on 100 goals in Portu 
Harry Kane treble as England demolish Montenegro to book Eur 
World Cup Qualifiers Injurytime goal saves India 
AizawlBagan opener on NOV 30 
Khongsai strikes MEGS winner 
Man Citys Bernardo Silva banned by FA Over tweet to Benjamin 
Footballer David Villa to retire at end of season 
TO reset the sort order Of the subitems to default value, click Reset 
Reset 
'Site 
edia Library 
Cancel 
Workbox

Now this Item can be rendered based on your requirement in your website.

Design a site like this with WordPress.com
Get started