步步為營 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.pswp.cn/news/536368.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/536368.shtml
英文地址,請注明出處:http://en.pswp.cn/news/536368.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

問題 J: 尋找復讀機【模擬】

問題 J: 尋找復讀機 時間限制: 1 Sec 內存限制: 128 MB 提交: 131 解決: 50 [提交] [狀態] [討論版] [命題人:admin] 題目描述 某個QQ群里一共有n個人&#xff0c;他們的編號是1..n&#xff0c;其中有一些人本質上是復讀機。 小A發現&#xff0c;如果一個人的本質是復讀機&…

windows下jenkins常見問題填坑

沒有什么高深的東西&#xff0c;1 2天的時間大多數人都能自己摸索出來&#xff0c;這里將自己遇到過的問題分享出來避免其他同學再一次挖坑. 目錄 1. 主從節點 2. Nuget自動包還原 3. powershell部署 4. 內網機器實現基于變化的構建 5. Github私有項目pull時限 所謂主從&#x…

Cow Contest【最短路-floyd】

Cow Contest POJ - 3660 N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors. …

【學習Android NDK開發】Type Signatures(類型簽名)

類型簽名&#xff08;Type Signatures&#xff09; (<Parameter 1 Type Code>[<Parameter 1 Class>];...)<Return Type Code> The JNI uses the Java VM’s representation of type signatures. Following Table shows these type signatures. Type Signatur…

Symantec(賽門鐵克)非受管檢測

為了查找局域網內沒有安裝賽門鐵克客戶端的IP&#xff0c;采用Symantec Endpoint Protect Manager 的非受管檢測機制進行網段掃描。 非受管檢測機制的原理是&#xff1a;每臺電腦開機時都會向同網段電腦發arp&#xff0c;當非受管檢測器接到arp請求時&#xff0c;會寫入本地的a…

SQL語句性能優化操作

1、對查詢進行優化&#xff0c;應盡量避免全表掃描&#xff0c;首先應考慮在where及order by涉及的列上建立索引。 2、應盡量避免在where子句中對字段進行null值判斷&#xff0c;創建表時NULL是默認值&#xff0c;但大多數時候應該使用NOT NULL&#xff0c;或者使用一個特殊的值…

sql語言特殊字符處理

我們都知道SQL Server查詢過程中&#xff0c;單引號“”是特殊字符&#xff0c;所以在查詢的時候要轉換成雙單引號“”。但這只是特殊字符的一個&#xff0c;在實際項目中&#xff0c;發現對于like操作還有以下特殊字符&#xff1a;下劃線“_”&#xff0c;百分號“%”&#xf…

小節

算法導論已學兩部分&#xff0c;第一部分是基礎知識&#xff0c;第二部分是排序。基礎知識介紹如何分析證明算法以及求時間復雜度。第二部分的排序學了很長時間。先是從簡單排序到復雜排序的一個過渡&#xff0c;打開了很多思路。然后就是無盡的算法分析。算法分析的時間比理解…

SPS2003升級到MOSS2007相關資料及問題總結

這幾天要把客戶的SPS2003門戶升級到MOSS2007的&#xff0c;客戶SPS2003門戶&#xff0c;數據26G&#xff0c;使用了自定義WebPart、自定義頁面、SSO等功能。升級過程中碰到大量問題。其中主要的問題有幾個&#xff0c;在這里把它們整理一下> 1、sps2003升級時&#xff0c;升…

Milking Time【動態規劃-dp】

Milking Time POJ - 3616 Bessie is such a hard-working cow. In fact, she is so focused on maximizing her productivity that she decides to schedule her next N (1 ≤ N ≤ 1,000,000) hours (conveniently labeled 0..N-1) so that she produces as much milk as po…

HTTP首部(1)

1、報文首部 HTTP協議的請求和響應必定包含HTTP首部&#xff0c;它包括了客戶端和服務端分別處理請求和響應提供所需要的信息。報文主體字兒是所需要的用戶和資源的信息都在這邊。  HTTP請求報文組成 方法&#xff0c;URL&#xff0c;HTTP版本&#xff0c;HTTP首部字段 HTTP響…

UVA272--TEX Quotes【字符串】

TEX Quotes UVA - 272 題目傳送門 題目大意&#xff1a;將輸入字符串中的所有對雙引號的做雙引號改為 &#xff0c;右雙引號改為 。 解決方法&#xff1a;遍歷一遍及時修改即可。 AC代碼&#xff1a; #include <cstdio> #include <iostream> #include <…

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 …

UVA----10082?WERTYU【字符串】

WERTYU UVA - 10082 題目傳送門 題目大意&#xff1a;按照所給的鍵盤樣式&#xff0c;以及錯誤的字符串&#xff0c;輸出正確的字符串&#xff0c;其輸入的每一個字符都按照鍵盤樣式向右錯移了一位。 解決方法&#xff1a;將整個鍵盤用數組存起來&#xff0c;遍歷一遍即可。…

關于C生成的匯編與C++生成的匯編在函數名稱上的差異

最近用到ucos&#xff0c;這個RTOS本身是用C語言和部分匯編編寫&#xff0c;而自己又打算用C來寫應用&#xff0c;在其中遇到幾個問題&#xff0c;一番折騰之后&#xff0c;讓我更加深刻認識到了在一些一般不注意的細節上&#xff0c;C與C的不同。 1、對于ucos&#xff0c;雖…

UVA401????????Palindromes【字符串】

Palindromes UVA - 401 題目傳送門 題目大意&#xff1a;給你一個字符串&#xff0c;判斷其是回文串還是鏡像串。 AC代碼&#xff1a; #include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <cstdlib> #…

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;…

UVA340????????Master-Mind Hints【數組】

Master-Mind Hints UVA - 340 題目傳送門 題目大意&#xff1a;先輸入一個整數n&#xff0c;表示有n個數字&#xff0c;下面第一行代表正確答案&#xff0c;其下每一行代表用戶猜的答案&#xff0c;需統計其有多少數字位置正確&#xff08;A&#xff09;&#xff0c;有多少數…

教你如何把自己從好友的QQ中刪除

在QQ中&#xff0c;有些人看了不太順眼&#xff0c;真不知當初為何讓他加自己為好友的&#xff01; 那有什么辦法&#xff0c;可以把自己從對方的QQ中刪除呢&#xff1f; 其實&#xff0c;用QQ就可以輕松搞定&#xff01; 讓我來為你支一招吧&#xff01; 打開QQ&#xff0…

UVA1583?Digit Generator

Digit Generator UVA - 1583 題目傳送門 題目大意&#xff1a;若x的各位數之和加上x本身等于y&#xff0c;則證明x是y的生成元&#xff0c;求輸入數字n的最小生成元。 AC代碼&#xff1a; #include <cstdio> #include <iostream> #include <algorithm> …