Creating Custom Timer Jobs in Sharepoint

来源:互联网 发布:win10无网络 无声音 编辑:程序博客网 时间:2024/05/08 05:21

查了很多资料,终于成功,记录下以备查阅。

1.首先建一个类库工程,建一个类文件用于定时器的处理,主要是继承SpJobDefinition,改写几个构造体和Execute的方法.基本代码的模式就是这个样子:文件名为mosstimer001.cs

using System;using System.Net;using System.Net.Mail;using Microsoft.SharePoint.Administration;using Microsoft.SharePoint;using System.Configuration;using System.Xml;namespace MOSStimer001{public class mosstimer001:SPJobDefinition{public mosstimer001() :base() { }///<summary>/// Initializes a new instance of the TaskLoggerJob class.///</summary>///<param name="jobName">Name of the job.</param>///<param name="service">The service.</param>///<param name="server">The server.</param>///<param name="targetType">Type of the target.</param>public mosstimer001(string jobName,SPService service,SPServer server,SPJobLockType targetType):base(jobName, service, server, targetType){}///<summary>/// Initializes a new instance of the TaskLoggerJob class.///</summary>///<param name="jobName">Name of the job.</param>///<param name="webApplication">The web application.</param>public mosstimer001(string jobName,SPWebApplication webApplication) :base(jobName, webApplication,null,SPJobLockType.ContentDatabase){this.Title ="MOSSTimer001";}///<summary>/// Executes the specified content db id.///</summary>///<param name="contentDbId">The content db id.</param>public override void Execute(Guid contentDbId){// get a reference to the current site collection's content databaseSPWebApplication webApplication =this.ParentasSPWebApplication;SPContentDataba secontentDb = webApplication.ContentDatabases[contentDbId];string splistname =ConfigurationManager.AppSettings.Get("ListName");string smtpHost =ConfigurationManager.AppSettings.Get("SmtpHost");string smtpName =ConfigurationManager.AppSettings.Get("SmtpName");string smtpPass =ConfigurationManager.AppSettings.Get("SmtpPass");string emailTitle =ConfigurationManager.AppSettings.Get("EmailTitle");string emailContent =ConfigurationManager.AppSettings.Get("EmailContent");string spwebName =ConfigurationManager.AppSettings.Get("WebName");string emailTo =ConfigurationManager.AppSettings.Get("EmailTo");string emailFrom =ConfigurationManager.AppSettings.Get("EmailFrom");SPSite oSiteCollection = contentDb.Sites[0];SPWeb web = oSiteCollection.AllWebs[spwebName];SPList taskList = web.Lists[splistname];SPQuery oQuery =newSPQuery();oQuery.Query ="<Where><Leq><FieldRef Name='" +taskList.Fields["Start Date"].InternalName +"'/><Value Type='DateTime'>2011-08-05</Value></Leq></Where>";//XmlConvert.EncodeName("Start Date")SPListItemCollection collItem = taskList.GetItems(oQuery);if(collItem !=null){if (collItem.Count > 0){foreach(SPListItem spListItemV in collItem){string strContent;strContent = emailContent.Replace("@name", spListItemV["Name"].ToString()).Replace("@startdate", spListItemV["Start Date"].ToString());SendEmail(smtpHost, smtpName, smtpPass, emailFrom, emailTo, emailTitle, strContent);}}}}private string SendEmail(string smtpHost,string smtpName,string smtpPass,string from,string to,string title,string content){MailAddress sendto =newMailAddress(to);MailAddress sendFrom =newMailAddress(from);MailMessage _mailMessage =new MailMessage(sendFrom, sendto);_mailMessage.Subject = title;_mailMessage.Body = content;_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;SmtpClient _smtpClient =new SmtpClient(smtpHost);_smtpClient.DeliveryMethod =SmtpDeliveryMethod.Network;_smtpClient.Credentials =new System.Net.NetworkCredential(smtpName, smtpPass);try{_smtpClient.Send(_mailMessage);return"OK";}catch(Exceptionex) {return ex.Message;}}}}


 

在此所有的mail信息都是读自配置信息,写一个OwsTimer.exe.config ,放到C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN 中

OwsTimer.exe.config文件实例:

<configuration>  <appSettings>   <add key="CBSS" value="server=;database=;user id=;password=" />  </appSettings></configuration>


2.再建一个类文件继承SPFeatureReceiver类。因为我们需要一个Feature来把我们的Timer部署到服务器上去,通过Feature Activated/deactivated来触发/关闭这个TimerJob。文件名为mosstimerinstaller.cs代码如下

using System;using Microsoft.SharePoint;using Microsoft.SharePoint.Administration;namespace MOSStimer001{class mosstimerinstaller:SPFeatureReceiver{const string TASK_JOB_NAME ="mosstimer001";///<summary>/// Occurs after a Feature is installed.///</summary>///<param name="properties">An<see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>public override void FeatureInstalled(SPFeatureReceiverProperties properties){}///<summary>/// Occurs when a Feature is uninstalled.///</summary>///<param name="properties">An<see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>public override void FeatureUninstalling(SPFeatureReceiverProperties properties){}///<summary>/// Occurs after a Feature is activated.///</summary>///<param name="properties">An<see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>public override void FeatureActivated(SPFeatureReceiverProperties properties){// register the the current webSPSite site = properties.Feature.ParentasSPSite;// make sure the job isn't already registeredforeach(SPJobDefinition job in site.WebApplication.JobDefinitions){if (job.Name == TASK_JOB_NAME)job.Delete();}// install the jobmosstimer001 taskLoggerJob =new mosstimer001(TASK_JOB_NAME, site.WebApplication);SPMinuteSchedule schedule =new SPMinuteSchedule();schedule.BeginSecond = 0;schedule.EndSecond = 59;schedule.Interval = 2;taskLoggerJob.Schedule = schedule;taskLoggerJob.Update();}///<summary>/// Occurs when a Feature is deactivated.///</summary>///<param name="properties">An<see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>public override void FeatureDeactivating(SPFeatureReceiverProperties properties){SPSite site = properties.Feature.ParentasSPSite;// delete the jobforeach(SPJobDefinition job in site.WebApplication.JobDefinitions){if (job.Name == TASK_JOB_NAME)job.Delete();}}}}


3.新增一个XML 文件用于Feature 的说明,文件名为Feature.xml

<?xmlversion="1.0"encoding="utf-8" ?><Featurexmlns="http://schemas.microsoft.com/sharepoint/"Id="1D777646-A208-48fa-AF98-3D944A90303A"Title="Timer Job 001"Description="Installs the task logger timer job feature to the current site collection."Version="1.0.0.0"Scope="Site"Hidden="TRUE"DefaultResourceFile="core"ReceiverAssembly="MOSStimer001, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6563b6c9d665c436"ReceiverClass="MOSStimer001.mosstimerinstaller"></Feature>


其中 Title 和 description 就是在 MOSS 的 Site Setting->Site Feature 中看到的内容,可修改, id 为 guid , 也可修改, scop 在此一定要设成 Site,否则会激活不了,但设成Site在MOSS的Site Feature页面上是看不到的,激活只能用命令. ReceiverAssembly 描述了工程生成的 dll ,在此用了强命名,所以有 PublicKeyToken, ReceiverClass 就是继承了 SPFeatureReceiver 的类

4.新建一个xml文件,文件名为 manifest.xml

<?xmlversion="1.0"encoding="utf-8" ?><Solutionxmlns="http://schemas.microsoft.com/sharepoint/"DeploymentServerType="WebFrontEnd"ResetWebServer="TRUE"SolutionId="A60961D9-69DD-476d-BADF-AB1C4F85B00E"><Assemblies> <AssemblyDeploymentTarget="GlobalAssemblyCache"Location="MOSStimer001.dll"/></Assemblies> <FeatureManifests><FeatureManifestLocation="TimerJob001\Feature.xml"/></FeatureManifests></Solution>


5. 新建一个文本文件,文件名为BuildSharePointPackage.ddf,内容如下


.OPTION Explicit.Set DiskDirectoryTemplate=CDROM.Set CompressionType=MSZIP.Set UniqueFiles=Off.Set Cabinet=On;**************************************************manifest.xmlbin\debug\MOSStimer001.dll.Set DestinationDir=TimerJob001Feature.xml;***End

 

其中 Feature.xml设置为在 TimerJob001目录下,这个需与 manifest.xml中的Feature.xml路径一致,dll文件也一样,在此dll没有指定目录.

6. build生成dll文件

7.生成 wsp文件,在此Feature.xml,manifest.xml和ddf文件在一个目录下. 在它们的相同目录下新建一个文本文件,文件名为 build.cmd,内容如下

@cd %~dp0makecab /F BuildSharePointPackage.ddf /D CabinetNameTemplate=MOSStimer001.wsp /D DiskDirectory1=bin\

 在此指定生成的wsp文件名为MOSStimer001.wsp, 放在 bin目录下. 其中的 CabinetNameTemplate 和 DiskDirectory1 也可以放在ddf文件中去.

8.将wsp文件发布到MOSS上去. 在此可以在bin目录下新建一个文本文件,文件名为 deploy.cmd,内容如下

@setlocal@pushd.@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0stsadm.exe -o addsolution -filename MOSStimer001.wspstsadm.exe -o deploysolution -name MOSStimer001.wsp -allowgacdeployment -local@pause@popd@endlocal

成功后可以在MOSS的Central Administration>Operations >Solution Management   中看到此wsp

9.同时在bin目录下新建一个文本文件,文件名为 retract.cmd,内容如下,用于从MOSS中卸载 wsp

@setlocal@pushd.@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0stsadm.exe -o retractsolution -name mosstimer001.wsp -localstsadm.exe -o deletesolution -name mosstimer001.wsp@pause@popd@endlocal

10.再在bin目录下建两个文件, activefeature.cmd 和 deactivefeature.cmd. 用于激活和失效 feature, 因为在此发布的wsp在MOSS的 site feature中是看不到的,只能用命令来做

activefeature.cmd内容如下:

@setlocal@pushd.@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0stsadm -o activatefeature -name TimerJob001 -url http://mossserver@pause@popd@endlocal

deactivefeature.cmd内容如下:

@setlocal@pushd.@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0stsadm -o deactivatefeature -name TimerJob001 -url http://mossserver@pause@popd@endlocal

 

此处的网址为 site collection 的地址.否则不能成功.


11.用VS命令行方式注册MSDN.SharePoint.Samples.SharePointWarmupJob.dll到GAC ,我也不确定这步是否必需.

clsd:cd D:\mossproject\test\SharePointWarmupJob.Source\SharePointWarmupJob"d:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf MSDN.SharePoint.Samples.SharePointWarmupJob"d:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if bin\Debug\MSDN.SharePoint.Samples.SharePointWarmupJob.dll 

每次都必需按照以下顺序操作才能正常调试

  • 把Assembly DLL放到 GAC
  • 命令行:iisreset
  • Deactivate feature, 然后activate feature.
  • 命令行:net stop SPTimerV3
  • 命令行:net start SPTimerV3
  • Visual Studio: Attach to process: OWSTIMER.EXE
  • 原创粉丝点击