Добавление задания таймера в SharePoint 2010 (Windows, О работе) 30.11.2011
Вот уже четвертый раз ко мне обращаются с вопросом "как программно создать новое задание таймера в SharePoint 2010?" - отвечаю заметкой, чтобы было куда в будущем направить интересующихся.
Открываем Visual Studio 2010. Создаем новый проект SharePoint 2010 -> Empty SharePoint Project.

Выбираем Deploy as farm solution

Создаем сделающий класс:
namespace Antonborisov
{
class ListTimerJob : SPJobDefinition
{
public ListTimerJob()
: base()
{
}
public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
: base(jobName, service, server, targetType)
{
}
public ListTimerJob(string jobName, SPWebApplication webApplication)
: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
{
this.Title = "List Timer Job";
}
public override void Execute(Guid contentDbId)
{
// get a reference to the current site collection's content database
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
// get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database
SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];
// create a new list Item, set the Title to the current day/time, and update the item
SPListItem newList = Listjob.Items.Add();
newList["Title"] = DateTime.Now.ToString();
newList.Update();
}
}
}
Теперь надо добавить новую Feature

и Event Receiver, который будет отвечать на добавление/удаление задания таймера

Далее необходимо внести соответсвующие изменения в класс нашего Event Recevier. Для нашего случая подойдет вот такой пример:
namespace Antonborisov.Features.Feature1
{
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
public class Feature1EventReceiver : SPFeatureReceiver
{
const string List_JOB_NAME = "ListLogger";
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
// make sure the job isn't already registered
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Name == List_JOB_NAME)
job.Delete();
}
// install the job
ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
schedule.Interval = 5;
listLoggerJob.Schedule = schedule;
listLoggerJob.Update();
}
// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
// delete the job
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Name == List_JOB_NAME)
job.Delete();
}
}
}
Перед развертыванием нашего решения, необходимо выбрать область действия Feature. Например коллекцию сайтов:

Теперь все готово к развертыванию:

После успешного развертывания осталось только зайти в SharePoint 2010 Central Administration -> Monitoring и в разделе Timer Jobs выбрать Review Job Definitions.

Открыв созданное задание таймера можно управлять расписанием его работы:


