项目需要写TimerJob,以前也大概知道原理,不过,开发过程中,还是遇到一些问题,网上看了好多博客,也有写的灰常好的,不过,自己还是想再写一下,也算是给自己一个总结,也算给大家多一个参考吧。
TimerJob项目结构,主要有两个Class,一个是用来定义TimerJob功能的,一个是用来部署开发好的TimerJob的,分别继承两个不同的类。如下图,先建一个如下结构的项目:
文件描述:
TimerJob定义类:ModifyTitle.cs(继承自SPJobDefinition)
TimerJob安装类:ModifyTitleInstall.cs(继承自SPFeatureReceiver)
激活TimerJob的Feature.xml
添加强命名,因为将来生成的dll是要放到GAC里面去的
添加引用:
引用Microsoft.SharePoint.dll文件,两个Class都需要添加下面命名空间
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
ModifyTitleInstall类
public class ModifyTitleInstall : SPFeatureReceiver
{
const string TimerJobName = "ModifyTitleTimerJob";//TimerJob的标题
//激活TimerJob的方法
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
//如果有相同的TimerJob,先删除
if (job.Title == TimerJobName)
{
job.Delete();
}
}
ModifyTitle modifyTitle = new ModifyTitle(TimerJobName, site.WebApplication);
SPMinuteSchedule minuteSchedule = new SPMinuteSchedule();//计时器对象
minuteSchedule.BeginSecond = 0;
minuteSchedule.EndSecond = 59;
minuteSchedule.Interval = 1;
modifyTitle.Schedule = minuteSchedule;
modifyTitle.Update();
//throw new NotImplementedException();
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Title == TimerJobName)
{
job.Delete();
}
}
//throw new NotImplementedException();
}
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
//throw new NotImplementedException();
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
//throw new NotImplementedException();
}
ModifyTitle类
public class ModifyTitle : SPJobDefinition
{
public ModifyTitle():base(){}
public ModifyTitle(string TimerName, SPWebApplication webapp) : base(TimerName, webapp, null, SPJobLockType.ContentDatabase)
{
//TimerJob的标题
this.Title = "定期修改Title的TimerJob";
}
public override void Execute(Guid targetInstanceId)
{
SPWebApplication webapp = this.Parent as SPWebApplication;
SPContentDatabase contentDB=webapp.ContentDatabases[targetInstanceId];
foreach (SPItem item in contentDB.Sites[0].RootWeb.Lists["TimerJob"].Items)
{
DateTime dt = Convert.ToDateTime(item["创建时间"].ToString());
item["标题"] = "今天是这个月的第" + dt.Day.ToString() + "天";
item.Update();
}
//base.Execute(targetInstanceId);
}
}