步步为营 SharePoint 开发学习笔记系列 七、SharePoint Timer Job 开发

概要

   项目需求要求我们每天晚上同步员工的一些信息到sharepoint 的user List ,我们决定定制开发sharepoint timer Job,Sharepoint timer Job是sharePoint的定时作业Job,需要安装、布曙到服务器上,而这里我只是介绍下Job开发的例子,以供大家学习用。

开发设计

我们需要新建两个类,TaskLoggerJob和TaskLoggerFeature,TaskLoggerJob实现这个Job具体做哪些工和,TaskLoggerFeature实现安装和卸载这个Job以及定义Job执行时间和方式。

在开发Job时需要引用如下Dll

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;

TaskLoggerJob设计代码如下:

    public class TaskLoggerJob : SPJobDefinition{#region [Fields]#endregion#region [Constructors]/// <summary>/// Initializes a new instance of the TaskLoggerJob class./// </summary>public TaskLoggerJob(): 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 TaskLoggerJob(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 TaskLoggerJob(string jobName, SPWebApplication webApplication): base(jobName, webApplication, null, SPJobLockType.Job){this.Title = "Task Logger";}#endregion#region [Public Methods]/// <summary>/// Executes the specified content db id./// </summary>/// <param name="contentDbId">The content db id.</param>public override void Execute(Guid contentDbId){try{// get a reference to the current site collection's content databaseSPWebApplication webApplication = this.Parent as SPWebApplication;SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];// get a reference to the "Tasks" list in the RootWeb of the first site collection in the content databaseSPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];// create a new task, set the Title to the current day/time, and update the itemSPListItem newTask = taskList.Items.Add();newTask["Title"] = DateTime.Now.ToString();newTask.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}#endregion#region [Private Methods]#endregion}

在TaskLoggerFeature时我们调用这个构造方法:

        /// <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 TaskLoggerJob(string jobName, SPWebApplication webApplication): base(jobName, webApplication, null, SPJobLockType.Job){this.Title = "Task Logger";}

来初始化SPJobDefinition方法,Job具体要做的事性我们实现这个方法:

        /// <summary>/// Executes the specified content db id./// </summary>/// <param name="contentDbId">The content db id.</param>public override void Execute(Guid contentDbId){try{// get a reference to the current site collection's content databaseSPWebApplication webApplication = this.Parent as SPWebApplication;SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];// get a reference to the "Tasks" list in the RootWeb of the first site collection in the content databaseSPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];// create a new task, set the Title to the current day/time, and update the itemSPListItem newTask = taskList.Items.Add();newTask["Title"] = DateTime.Now.ToString();newTask.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}

在这个方法里我们可以同事实现很多任务,而我们这里只是改变了它的title。

下面我们来讲解TaskLoggerFeature的代码设计,首先引用:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

而后代码如下:

    public class TaskLoggerFeature : SPFeatureReceiver{#region [Override Methods]/// <summary>/// Active the feature/// </summary>/// <param name="properties"></param>public override void FeatureActivated(SPFeatureReceiverProperties properties){SPSite site = properties.Feature.Parent as SPSite;SPSite currentSite = null;try{SPSecurity.RunWithElevatedPrivileges(delegate{currentSite = new SPSite(site.Url);});this.InstallTaskLoggerJob(currentSite);}catch (Exception ex){LogHepler.InitConfigListSiteUrl(site.Url);LogHepler.LogToShrepointList(ex);}finally{if (currentSite != null){currentSite.Dispose();}}}/// <summary>/// Deactive the feature/// </summary>/// <param name="properties"></param>public override void FeatureDeactivating(SPFeatureReceiverProperties properties){SPSite site = properties.Feature.Parent as SPSite;SPSite currentSite = null;try{SPSecurity.RunWithElevatedPrivileges(delegate{currentSite = new SPSite(site.Url);});SPWebApplication webApp = currentSite.WebApplication;this.UninstallTaskLoggerJob(webApp);}catch (Exception ex){LogHepler.InitConfigListSiteUrl(site.Url);LogHepler.LogToShrepointList(ex);}finally{if (currentSite != null){currentSite.Dispose();}}}/// <summary>/// Method that is executed when the feature end the installation/// </summary>/// <param name="properties"></param>public override void FeatureInstalled(SPFeatureReceiverProperties properties){}/// <summary>/// Method that is executed when the feature is unistalled/// </summary>/// <param name="properties"></param>public override void FeatureUninstalling(SPFeatureReceiverProperties properties){}#endregion#region [Private Methods]/// <summary>/// method to install the job/// </summary>/// <param name="web"></param>private void InstallTaskLoggerJob(SPSite site){TaskLoggerJob jobDef = new TaskLoggerJob("TaskLoggerJob", site.WebApplication);jobDef.Title = "TaskLoggerJob";jobDef.Properties.Add("SiteUrl", site.Url);this.InstallDayJob(jobDef, site, 23);//this.InstallHourJob(jobDef, site, 2);//this.InstallMinuteJob(jobDef, site, 10, 10);}/// <summary>/// Method to unistall a job/// </summary>/// <param name="web">The SPWeb where need to remove the job</param>private void UninstallTaskLoggerJob(SPWebApplication webApp){try {SPJobDefinitionCollection jobColl = webApp.JobDefinitions;if (jobColl != null){List<Guid> idsToRemove = new List<Guid>();foreach (SPJobDefinition jobDef in jobColl){if (!String.IsNullOrEmpty(jobDef.Title) && jobDef.Title.StartsWith("TaskLoggerJob")){idsToRemove.Add(jobDef.Id);}}if (idsToRemove.Count > 0){foreach (Guid gd in idsToRemove){jobColl.Remove(gd);}}}}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Method to install the job that will execute by hour/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="minute">The minute to start the job in that hour</param>private void InstallDayJob(SPJobDefinition jobDef, SPSite site, int hour){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPDailySchedule daySched = new SPDailySchedule();daySched.BeginHour = hour;daySched.BeginMinute = 0;daySched.BeginSecond = 0;daySched.EndHour = hour;daySched.EndMinute = 0;daySched.EndSecond = 0;jobDef.Schedule = daySched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Method to install the job that will execute by hour/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="minute">The minute to start the job in that hour</param>private void InstallHourJob(SPJobDefinition jobDef, SPSite site, int minute){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPHourlySchedule hourSched = new SPHourlySchedule();hourSched.BeginMinute = minute;jobDef.Schedule = hourSched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Method to install the job that will execute by minute/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="secound">The seconds to start the job in that minute</param>private void InstallMinuteJob(SPJobDefinition jobDef, SPSite site, int second, int interval){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPMinuteSchedule minSched = new SPMinuteSchedule();minSched.Interval = interval;minSched.BeginSecond = second;jobDef.Schedule = minSched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Get the JobDefinition to install or remove/// </summary>/// <param name="Title">Title of the job</param>/// <param name="jobCollection">The JobCollection to find the job</param>/// <returns>JbDefinition that found in this collection</returns>private SPJobDefinition GetJobDeffinition(string Title, SPJobDefinitionCollection jobCollection){SPJobDefinition result = null;if (jobCollection != null){foreach (SPJobDefinition job in jobCollection){if (job.Title.Equals(Title)){result = job;break;}}}return result;}#endregion}

下面这个方法是激活这个Job的feature,在sharepoint里每一个Job都有一个feature来讲行实现,它会生成相应的feature的xml方件:

        /// <summary>/// Active the feature/// </summary>/// <param name="properties"></param>public override void FeatureActivated(SPFeatureReceiverProperties properties){SPSite site = properties.Feature.Parent as SPSite;SPSite currentSite = null;try{SPSecurity.RunWithElevatedPrivileges(delegate{currentSite = new SPSite(site.Url);});this.InstallTaskLoggerJob(currentSite);}catch (Exception ex){LogHepler.InitConfigListSiteUrl(site.Url);LogHepler.LogToShrepointList(ex);}finally{if (currentSite != null){currentSite.Dispose();}}}
 
 
卸载这个Job的方法如下:
        /// <summary>/// Deactive the feature/// </summary>/// <param name="properties"></param>public override void FeatureDeactivating(SPFeatureReceiverProperties properties){SPSite site = properties.Feature.Parent as SPSite;SPSite currentSite = null;try{SPSecurity.RunWithElevatedPrivileges(delegate{currentSite = new SPSite(site.Url);});SPWebApplication webApp = currentSite.WebApplication;this.UninstallTaskLoggerJob(webApp);}catch (Exception ex){LogHepler.InitConfigListSiteUrl(site.Url);LogHepler.LogToShrepointList(ex);}finally{if (currentSite != null){currentSite.Dispose();}}}

 

Job的执行时间可以按分、时、天、月、年来执行可以进行如下定义,分、时、天。概据你的需要来执行。

        /// <summary>/// Method to install the job that will execute by hour/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="minute">The minute to start the job in that hour</param>private void InstallDayJob(SPJobDefinition jobDef, SPSite site, int hour){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPDailySchedule daySched = new SPDailySchedule();daySched.BeginHour = hour;daySched.BeginMinute = 0;daySched.BeginSecond = 0;daySched.EndHour = hour;daySched.EndMinute = 0;daySched.EndSecond = 0;jobDef.Schedule = daySched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Method to install the job that will execute by hour/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="minute">The minute to start the job in that hour</param>private void InstallHourJob(SPJobDefinition jobDef, SPSite site, int minute){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPHourlySchedule hourSched = new SPHourlySchedule();hourSched.BeginMinute = minute;jobDef.Schedule = hourSched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}/// <summary>/// Method to install the job that will execute by minute/// </summary>/// <param name="jobDef">The JobDefinition to apply</param>/// <param name="web">The SPWeb that will execute the job</param>/// <param name="secound">The seconds to start the job in that minute</param>private void InstallMinuteJob(SPJobDefinition jobDef, SPSite site, int second, int interval){try{SPWebApplication webApp = site.WebApplication;SPJobDefinitionCollection jboColl = webApp.JobDefinitions;SPMinuteSchedule minSched = new SPMinuteSchedule();minSched.Interval = interval;minSched.BeginSecond = second;jobDef.Schedule = minSched;SPJobDefinition oldJob = this.GetJobDeffinition(jobDef.Title, jboColl);if (oldJob != null){jboColl.Remove(oldJob.Id);webApp.Update();}jboColl.Add(jobDef);webApp.Update();}catch (Exception ex){LogHepler.LogToShrepointList(ex);}}

 

在完成了上面的代码设计后,我们接着就需要把Job布曙到服务器中。

要以上代码生成Windows SharePoint Solution Package (*.WSP) 来布曙。

步骤如下:

一、首先进入sharePoint Central administrator v3 管理页面,选择Operation下的Solution Management

image

二、检索TaskLoggerJob.wsp

如果以前安装过这个Job先要卸载,再安装。 
三、执行命令   stsadm -o addsolution -filename "TaskLoggerJob.wsp"  添加Job的solution

四、执行命令 stsadm -o deactivatefeature -name TaskLoggerJob -url http://[site]/
      而后再执行命令  stsadm -o execadmsvcjobs
五、执行命令 stsadm -o activatefeature -name TaskLoggerJob -url http://[site]/
      而后再执行命令  stsadm -o execadmsvcjobs

总结

sharepoint timer job是用来完成系统定里执行的一此任务,是由这个进程完成的OWSTIMER.EXE .

作者:spring yang

出处:http://www.cnblogs.com/springyangwc/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

转载于:https://www.cnblogs.com/springyangwc/archive/2011/07/25/2115963.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/536368.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows下jenkins常见问题填坑

没有什么高深的东西&#xff0c;1 2天的时间大多数人都能自己摸索出来&#xff0c;这里将自己遇到过的问题分享出来避免其他同学再一次挖坑. 目录 1. 主从节点 2. Nuget自动包还原 3. powershell部署 4. 内网机器实现基于变化的构建 5. Github私有项目pull时限 所谓主从&#x…

HTTP首部(1)

1、报文首部 HTTP协议的请求和响应必定包含HTTP首部&#xff0c;它包括了客户端和服务端分别处理请求和响应提供所需要的信息。报文主体字儿是所需要的用户和资源的信息都在这边。  HTTP请求报文组成 方法&#xff0c;URL&#xff0c;HTTP版本&#xff0c;HTTP首部字段 HTTP响…

XMLHttpRequest+WebForm模式(接口IHttpHandler)实现ajax

首先引入ajax.js文件 创建xmlhttpRequest对象 Code//创建XMLHttpRequest对象var xmlHttp;function newXMLHttpRequest() { if (window.XMLHttpRequest) { xmlHttp new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xmlHttp …

IIS 5 与IIS 6 原理介绍

[ 转] ASP.NET Process Model之一&#xff1a;IIS 和 ASP.NET ISAPI 前几天有一个朋友在MSN上问我“ASP.NET 从最初的接收到Http request到最终生成Response的整个流程到底是怎样的&#xff1f;”我觉得这个问题涉及到IIS和ASP.NETASP.NET Runtime的处理模型的问题&#xff0c;…

SharePoint v3:忘掉模拟用户Impersonate,SPSecurity.RunWithElevatedPrivileges来了

回顾&#xff1a; 在SharePoint V2 大家应该都用过模拟用户Impersonate这个功能&#xff0c; 这个功能用来暂时提升某个用户的权限&#xff0c;比如某个普通用户的本来不能修改某个列表的值&#xff0c;但是我们功能需要在修改。 缺点&#xff1a; 我们使用这个模拟用户功能…

螺旋方阵问题【数组】

输入n&#xff0c;输出n阶螺旋方阵&#xff0c;下面为5阶螺旋方阵&#xff1a;1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9 下面为我的代码&#xff1a; #include <cstdio> #include <iostream> #include &…

马鞍点问题【数组】

如果在一矩阵中元素A[i][j]满足A[i][j]为第i行的最小值&#xff0c;第j行的最大值&#xff0c;则称这个元素为这个矩阵的马鞍点&#xff0c;求m*n矩阵所有的马鞍点。若需求一个矩阵的所有马鞍点&#xff0c;其实只需将矩阵的每行的最小值与每列的最大值分别求出存在相应的数组中…

求二叉树节点个数、叶子节点、节点层次与宽度

需实现&#xff1a;&#xff08;1&#xff09;输出二叉树b的节点个数 &#xff08;2&#xff09;输出二叉树b的叶子节点个数 &#xff08;3&#xff09;求二叉树b中指定节点值&#xff08;假设所有节点值不同&#xff09;的节点的层次。 &#xff08;4&#xff09;利用层次遍历…

【数学】Chaarshanbegaan at Cafebazaar

题目描述 Chaarshanbegaan is a gathering event at Cafebazaar similar to TGIF events at Google. Some entertainment programs like pantomime, foosball, Xbox/PS4, and several board games are part of the event. You are going to set up a dart game in Chaarshanbe…

【思维】Congestion Charging Zone

题目描述 Tehran municipality has set up a new charging method for the Congestion Charging Zone (CCZ) which controls the passage of vehicles in Tehran’s high-congestion areas in the congestion period (CP) from 6:30 to 19:00. There are plate detection came…

【二分】LED

题目描述 A Light-Emitting Diode (LED) is a semiconductor light source, which emits light when an electric current of voltage higher than a threshhold is applied to its leads. ACM R&D recently reported that they have succesfully developed a new LED, na…

【模拟】Thanks, TuSimple!

题目链接&#xff1a;http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId5979 Thanks, TuSimple! Time Limit: 1 Second Memory Limit: 65536 KB In the very first sentence of the very first problem, we would like to give our sincere thanks to TuSimple,…

【二维差分】Monitor

Monitor 题目&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid6514 Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 163840/163840 K (Java/Others) Total Submission(s): 600 Accepted Submission(s): 190 Problem Description Xiaoteng has a la…

【二分+二维前缀和】Largest Allowed Area

Largest Allowed Area 时间限制: 1 Sec 内存限制: 128 MB 提交: 146 解决: 54 [提交] [状态] [命题人:admin] 题目描述 A company is looking for land to build its headquarters. It has a lot of money and can buy as many land patches as it needs. Its goal, howev…

【数学】Floating-Point Hazard

Floating-Point Hazard 时间限制: 1 Sec 内存限制: 128 MB 提交: 106 解决: 42 [提交] [状态] [命题人:admin] 题目描述 Given the value of low, high you will have to find the value of the following expression: If you try to find the value of the above express…

【线段树】Segment Tree

Segment Tree 时间限制: 1 Sec 内存限制: 512 MB 提交: 107 解决: 23 [提交] [状态] [命题人:admin] 题目描述 Mcginn opens the code which he wrote 25 years ago. Clever Mcginn wants to know how many positive interger n satisfied that the maximum c can reach w…

扶桑号战列舰【RMQ+分治】

扶桑号战列舰 时间限制: 1 Sec 内存限制: 128 MB Special Judge 提交: 197 解决: 63 [提交] [状态] [命题人:admin] 题目描述 众所周知&#xff0c;一战过后&#xff0c;在世界列强建造超无畏级战列舰的竞争之中&#xff0c;旧日本海军根据“个舰优越主义”&#xff0c;建造了扶…

大凤号装甲空母【找规律+矩阵快速幂】

大凤号装甲空母 时间限制: 1 Sec 内存限制: 128 MB 提交: 108 解决: 15 [提交] [状态] [命题人:admin] 题目描述 大凤号航空母舰很喜欢算术。 它&#xff0c;是旧日本海军中最为先进的航空母舰。 它&#xff0c;是旧日本海军中最为短命的航空母舰。 同时&#xff0c;她还是最平…

Degree Sequence of Graph G【模拟】

Degree Sequence of Graph G 时间限制: 1 Sec 内存限制: 128 MB 提交: 362 解决: 92 [提交] [状态] [命题人:admin] 题目描述 Wang Haiyang is a strong and optimistic Chinese youngster. Although born and brought up in the northern inland city Harbin, he has deep lov…

【动态规划】魔法石矿

【动态规划】魔法石矿 时间限制: 1 Sec 内存限制: 64 MB 提交: 116 解决: 27 [提交] [状态] [命题人:admin] 题目描述 为了找到回家的路&#xff0c;张琪曼施展魔法&#xff0c;从高维空间召唤出了一种叫作“读者”的生物&#xff0c;据说“读者”这种生物无所不能&#xff0c;…