首页 > 代码库 > 创建SharePoint 2010 Timer Job

创建SharePoint 2010 Timer Job

好久没有写博客了。最近在使用SharePoint 2010中Timer Job的功能,有了一点心得,分享一下。

我个人认为SharePoint Timer Job和Windows Service或者是Schedule很相似,就是enable之后可以定时执行。开发的步骤如下:

1.   在VS中新建一个Class,这个Class继承Microsoft.SharePoint.Administration.SPJobDefinition,实现的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Mike.TimeJob
{
    public class MyFirstTimeJob:SPJobDefinition
    {
        public MyFirstTimeJob()
            :base()
        {}
        
        public MyFirstTimeJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            :base(jobName,service,server,targetType)
        {}
        
        public MyFirstTimeJob(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Mike First Timer Job";
        }

        public override void Execute(Guid targetInstanceId)
        {
            // get a reference to the current site collection‘s content database
            SPWebApplication webApplication = this.Parent as SPWebApplication;
            SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];

            // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
            SPList taskLlist=contentDb.Sites[0].RootWeb.Lists["Tasks"];

            //create a new task, set the Title to the current day/time, and update the item
            SPListItem newTask = taskLlist.Items.Add();
            newTask["Title"] = DateTime.Now.ToString();
            newTask.Update();            
        }
    }
}
MyFirstTimeJob这个类最关键的就是需要override Execute方法,这里面可以写你自己想要实现的业务逻辑,我这里就是向Tasks List中每次新增一个时间信息,这个类需要注册到GAC中,是需要强命名的。


2. 在VS中新建第二个Class,这个Class是MyFirstTimeJob的安装类,在SharePoint Feature被激活的时候使用,这个Class继承了Microsoft.SharePoint.Administration.SPFeatureReceiver,实现的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Mike.TimeJob
{
    public class MyFirstTimeJobInstaller:SPFeatureReceiver
    {
        const string JOB_NAME = "MyFirstTimeJob";

        public override void  FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        public override void  FeatureUninstalling(SPFeatureReceiverProperties properties)
        {

        }

        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 == JOB_NAME)
                job.Delete();
            }
            // install the job
            MyFirstTimeJob myjob = new MyFirstTimeJob(JOB_NAME, site.WebApplication);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;
            myjob.Schedule = schedule;
            myjob.Update();
        }

        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 == JOB_NAME)
                    job.Delete();
            }
        }
    }
}

MyFirstTimeJobInstaller类中FeatureDeactivating方法用于在Feature被Disable时将已经存在的SPJobDefinition实例删除,FeatureActivated方法用于删除已经存在的SPJobDefinition实例,然后再新建实例,并设置Schedule,Schedule可以有SPYearlySchedule、SPMonthlySchedule、SPDailySchedule、SPHourlySchedule、SPMinuteSchedule等等,具体可以去查MSDN。

3. 将这2个Class注册到GAC中,因为是同一个Assembly,得到一个PublicKey。

安装GAC的命令

gacutil -i 目录\Mike.TimeJob.dll

4. 在创建Feature.XML文件

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
         Id="D4C9BB6B-E95D-4066-A0BA-EE5AAE79E3B3"
         Title="Mike First Timer Job"
         Description="Mike Hu‘s first timer job for adding now to tasks list"
         Scope="Site"
         Hidden="TRUE"
         Version="1.0.0.0"
         ReceiverAssembly="Mike.TimeJob, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d747f4e6e693450e"
         ReceiverClass="Mike.TimeJob.MyFirstTimeJobInstaller">
</Feature>

这里Feature中的PublicKeyToken填写的是第3步得到的Public Key.将这个feature.xml文件copy到C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\MyFirstTimeJob_Feature1中,注意MyFirstTimeJob_Feature1是自己创建的。


5. 安装Feature

stsadm -o installfeature -filename MyFirstTimeJob_Feature1\feature.xml -force


6. 重新启动ISS

iisreset


7. 激活Feature

stsadm -o activatefeature -filename MyFirstTimeJob_Feature1\feature.xml -urlhttp://prsgi0001

其中http://prsgi0001表所起作用的Web Application,这是Timer Job已经安装成功,并设置好了Shedule。


8. stop SharePoint 2010 Timer
net stop sptimerv4

9. start SharePoint 2010 Timer
net start sptimerv4

这样在Central Administration--> Monitoring --> Timer Jobs --> Review Job Definition中找到安装好的Timer Job。


全部完成,并可以成功运行了。


10. 如果需Debug,需要attach to process到OWSTIMER.EXE这个process中。


参考:Andrew Connell, Creating Custom SharePoint Timer Jobs