博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
步步为营 SharePoint 开发学习笔记系列 七、SharePoint Timer Job 开发
阅读量:6668 次
发布时间:2019-06-25

本文共 18504 字,大约阅读时间需要 61 分钟。

概要

   项目需求要求我们每天晚上同步员工的一些信息到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]        ///         /// Initializes a new instance of the TaskLoggerJob class.        ///         public TaskLoggerJob()            : base()        {        }        ///         /// Initializes a new instance of the TaskLoggerJob class.        ///         /// Name of the job.        /// The service.        /// The server.        /// Type of the target.        public TaskLoggerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)            : base(jobName, service, server, targetType)        {        }        ///         /// Initializes a new instance of the TaskLoggerJob class.        ///         /// Name of the job.        /// The web application.        public TaskLoggerJob(string jobName, SPWebApplication webApplication)            : base(jobName, webApplication, null, SPJobLockType.Job)        {            this.Title = "Task Logger";        }        #endregion        #region [Public Methods]        ///         /// Executes the specified content db id.        ///         /// The content db id.        public override void Execute(Guid contentDbId)        {            try            {                // get a reference to the current site collection's content database                SPWebApplication 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 database                SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];                // create a new task, set the Title to the current day/time, and update the item                SPListItem newTask = taskList.Items.Add();                newTask["Title"] = DateTime.Now.ToString();                newTask.Update();            }            catch (Exception ex)            {                LogHepler.LogToShrepointList(ex);            }        }        #endregion        #region [Private Methods]        #endregion    }

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

///         /// Initializes a new instance of the TaskLoggerJob class.        ///         /// Name of the job.        /// The web application.        public TaskLoggerJob(string jobName, SPWebApplication webApplication)            : base(jobName, webApplication, null, SPJobLockType.Job)        {            this.Title = "Task Logger";        }

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

///         /// Executes the specified content db id.        ///         /// The content db id.        public override void Execute(Guid contentDbId)        {            try            {                // get a reference to the current site collection's content database                SPWebApplication 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 database                SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];                // create a new task, set the Title to the current day/time, and update the item                SPListItem 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]        ///         /// Active the feature        ///         ///         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();                }            }        }        ///         /// Deactive the feature        ///         ///         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();                }            }        }        ///         /// Method that is executed when the feature end the installation        ///         ///         public override void FeatureInstalled(SPFeatureReceiverProperties properties)        {        }        ///         /// Method that is executed when the feature is unistalled        ///         ///         public override void FeatureUninstalling(SPFeatureReceiverProperties properties)        {        }        #endregion        #region [Private Methods]        ///         /// method to install the job        ///         ///         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);        }        ///         /// Method to unistall a job        ///         /// The SPWeb where need to remove the job        private void UninstallTaskLoggerJob(SPWebApplication webApp)        {            try             {                SPJobDefinitionCollection jobColl = webApp.JobDefinitions;                if (jobColl != null)                {                    List
idsToRemove = new List
(); 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); } } ///
/// Method to install the job that will execute by hour /// ///
The JobDefinition to apply ///
The SPWeb that will execute the job ///
The minute to start the job in that hour 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); } } ///
/// Method to install the job that will execute by hour /// ///
The JobDefinition to apply ///
The SPWeb that will execute the job ///
The minute to start the job in that hour 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); } } ///
/// Method to install the job that will execute by minute /// ///
The JobDefinition to apply ///
The SPWeb that will execute the job ///
The seconds to start the job in that minute 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); } } ///
/// Get the JobDefinition to install or remove /// ///
Title of the job ///
The JobCollection to find the job ///
JbDefinition that found in this collection
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方件:

///         /// Active the feature        ///         ///         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的方法如下:
///         /// Deactive the feature        ///         ///         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的执行时间可以按分、时、天、月、年来执行可以进行如下定义,分、时、天。概据你的需要来执行。

///         /// Method to install the job that will execute by hour        ///         /// The JobDefinition to apply        /// The SPWeb that will execute the job        /// The minute to start the job in that hour        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);            }        }        ///         /// Method to install the job that will execute by hour        ///         /// The JobDefinition to apply        /// The SPWeb that will execute the job        /// The minute to start the job in that hour        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);            }        }        ///         /// Method to install the job that will execute by minute        ///         /// The JobDefinition to apply        /// The SPWeb that will execute the job        /// The seconds to start the job in that minute        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

二、检索TaskLoggerJob.wsp

如果以前安装过这个Job先要卸载,再安装。 

三、执行命令   stsadm -o addsolution -filename "TaskLoggerJob.wsp"  添加Job的solution

四、执行命令 stsadm -o deactivatefeature -name TaskLoggerJob -url

      而后再执行命令  stsadm -o execadmsvcjobs
五、执行命令 stsadm -o activatefeature -name TaskLoggerJob -url
      而后再执行命令  stsadm -o execadmsvcjobs

总结

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

作者:

出处:

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

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

你可能感兴趣的文章
Kinect 开发小记:穿越艾泽拉斯,调戏红龙女王
查看>>
C#实现ACCESS数据库备份还原
查看>>
机房收费系统中的Grid++Report报表设计器的应用
查看>>
通过Wifi调试Android应用
查看>>
Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
查看>>
ZeroMQ接口函数之 :zmq_getsockopt – 获取ZMQ socket的属性
查看>>
ThreadPoolExecutor使用介绍
查看>>
用C++/CLI搭建C++和C#之间的桥梁(四)—— 网络资源
查看>>
纳米技术的起源与发展
查看>>
launchpad, jira, github
查看>>
JavaWeb学习笔记——XML和SAX解析区别
查看>>
hdu1716排列2(stl:next_permutation+优先队列)
查看>>
Java 8 时间日期库的20个使用示例
查看>>
Android系统开发(4)——Autotools
查看>>
Nginx教程(一) Nginx入门教程
查看>>
【cocos2d-x 3.7 飞机大战】 决战南海I (十) 游戏主场景
查看>>
ORM进阶:Hibernate框架搭建及开发
查看>>
scala Wordcount
查看>>
单细胞文献分析 Quantitative single-cell rna-seq with unique molecular identifers
查看>>
面试2
查看>>