SharePoint中开发自定义Timer Job
1. Timer Job简介
在SharePoint中有一个服务SharePoint timer service(owstimer.exe),这个服务用来进行异步处理一些SharePoint的数据,创建web application等等,为了缓解站点w3wp.exe的压力,而且Timer 服务可以说是占据了SharePoint的半边天,没有他那么SharePoint将不能正常工作
2. Timer Job 作用
很多时候我们需要定期自动去处理一些数据,例如:为了不影响业务性能有些数据在非工作时间系统自动处理,那么timer job就能够帮我们实现这个,在SharePoint中有很多原生的job,而且也支持自定义timer job去满足业务需求。
3. timer job的基类:
一般我们要编写一个自定义的timer job的话,我们需要继承SPJobDefinition ,然后重写Execute方法,在这个方法里面添加自己的业务逻辑代码,如下:
public class MyTimerJobDefinition : SPJobDefinition
{
public MyTimerJobDefinition () : base() { }
public MyTimerJobDefinition (SPWebApplication webApp) :
base(SapConstant.ReminderJobName, webApp, null, SPJobLockType.Job)
{}
public override void Execute(Guid targetInstanceId)
{
//base.Execute(targetInstanceId);
try
{
SPWebApplication webApp = this.Parent as SPWebApplication;
// todo....
}
catch (Exception ex)
{
//log
}
}
public override void Delete()
{
try
{
base.Delete();
}
catch (Exception ex)
{
//log
}
}
}
4. 自定义Timer Job的安装
在SharePoint中大多数自定义功能都是通过Feature去安装和部署的,当然Timer Job也是不例外的, 在项目中添加一个feature,然后重写相应的激活方法,如下:
[Guid("418ce432-d5e5-4fff-9a3f-ec46445bc105")]
public class Feature1EventReceiver : SPFeatureReceiver
{
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
DeleteJob(webApp.JobDefinitions);
MyTimerJobDefinition simpleJob = new MyTimerJobDefinition(webApp);
SPDailySchedule schedule = new SPDailySchedule();
schedule.BeginHour = 9;
schedule.BeginMinute = 1;
schedule.BeginSecond = 1;
schedule.EndSecond = 30;
schedule.EndMinute = 6;
schedule.EndHour = 12;
simpleJob.Schedule = schedule;
simpleJob.Title = "My Custom Timer";
simpleJob.Update();
}
catch (Exception ex)
{
//log
}
}
// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
try
{
SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
DeleteJob(webApp.JobDefinitions);
}
catch (Exception ex)
{
//log
}
}
private void DeleteJob(SPJobDefinitionCollection jobs)
{
foreach (SPJobDefinition job in jobs)
{
if (job.Name.Equals("JobName",
StringComparison.OrdinalIgnoreCase))
{
job.Delete();
}
}
}
}
原文:http://blog.csdn.net/gihow/article/details/40660037