概要

项目需求要求我们每天晚上同步员工的一些信息到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

二、检索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

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

  1. Windows驱动开发学习笔记(七)—— 多核同步内核重载

    Windows驱动开发学习笔记(七)-- 多核同步 基础知识 并发与同步 分析 InterlockedIncrement 原子操作相关API 内核文件 多核同步 临界区 示例一:错误的临界区 示例二: ...

  2. Kinect开发学习笔记之(二)Kinect开发学习资源整理

    Kinect开发学习笔记之(二)Kinect开发学习资源整理 zouxy09@qq.com http://blog.csdn.net/zouxy09 刚刚接触Kinect,在网上狂搜资料,获得了很多有 ...

  3. Kinect开发学习笔记之(三)Kinect开发环境配置

    Kinect开发学习笔记之(三)Kinect开发环境配置 zouxy09@qq.com http://blog.csdn.net/zouxy09 我的Kinect开发平台是: Win7 x86 + V ...

  4. 步步为营 .NET 设计模式学习笔记系列总结

    设计模式我从开篇到23种设计模式的讲解总共花了进两个月的时间,其间有很多读者给我提出了很好的建议,同时也指出了我的不足,对此我表示感谢,正是由于很多读者的支持我才能坚持的写到最后.在此表示我真诚的谢意 ...

  5. Windows 8 Directx 开发学习笔记(七)水波纹的实现

    使用DirectX实际开发中,模型的形状不可能都是一成不变,只依靠移动摄像机去实现动画.这里用实时更新顶点缓冲的方式生成一个水波模型,最终效果类似向水面扔石子时出现的水波纹.有了上一篇建立好的模型,实 ...

  6. android开发学习笔记系列(6)--代码规范

    在开发android的时候,我对自己写的代码很是不满,原因在于自己看到别人的代码,很是头痛,原因很简单,别人写的代码,我就要去猜他的意思,极其烦恼,嗯,就是他没有遵循代码规范,因此我在博客园上寻找一篇 ...

  7. java 仿qq登录界面7.1_安卓开发学习笔记(七):仿写腾讯QQ登录注册界面

    这段代码的关键主要是在我们的相对布局以及线性布局上面,我们首先在总体布局里设置为线性布局,然后再在里面设置为相对布局,这是一个十分常见的XML布局模式. 废话不多说,直接上代码: 一.activity ...

  8. GTK+图形化应用程序开发学习笔记(七)—标签构件.事件盒构件

    一.标签构件 标签构件(GtkLabel)是GTK中最常见的构件,它是静态的不可编辑的字段.在屏幕上,常常用标号说明其他字段.在按钮上设置标签用来说明按钮,或者放在其他字段的旁边对该字段提供说明.它不 ...

  9. Hybrid混合开发学习笔记(1)混合应用开发定义和常见问题

    一.什么是混合应用 混合应用是指同时使用前端技术与原生技术开发的 App.通常由前端负责大部分界面开发和业务逻辑,原生负责封装原生功能供前端调用,二者以 WebView 作为媒介建立通信,从而既拥有 ...

最新文章

  1. 复现经典:《统计学习方法》第1章 统计学习方法概论
  2. 新闻发布项目——接口类(UserDao)
  3. 服务框架及服务治理组件——业界调研
  4. m1MacBook的TensorFlow虚拟环境---pytables的安装
  5. 恶意攻击防范之信用卡业务的计数器反欺诈
  6. 模块化思想——粤嵌GEC6818读取图片宽度、高度、色深
  7. 看了这个视频都想辞职了
  8. 【回归预测-LSTM预测】基于布谷鸟算法优化LSTM实现数据回归预测含Matlab代码
  9. 学习有法,事半功倍 — 在线学习的10个技巧
  10. Linux常用软件包安装工具及配置方法(apt-get, pip, dpkg)
  11. 历史上有哪些最凶计算机病毒?
  12. 如何通过Photoshop制作Gif图片(把几张图片合成一张Gif图片)
  13. 基于Java毕业设计在线装机报价系统源码+系统+mysql+lw文档+部署软件
  14. Windows10系统桌面美化,定制自己的专属桌面.
  15. When inserting 1, 2, 3, 6, 5, and 4 one by one into an initially empty AVL tree,which kinds of rotat
  16. Windows下载安装Cytoscape3.8.2
  17. 省级交通运输行政执法综合管理信息系统工程方案
  18. 06.论Redis持久化的几种方式
  19. 金纳米粒子修饰MIL-101骨架材料(AuNPs/MIL-101)/负载COF-TpPa-1(Au NPs/COF-TpPa-1)|齐岳试剂
  20. 第一次 之 挑灯夜战

热门文章

  1. 当前完整路径_详解关键路径法,这可能是你找得到最详细的了
  2. php keep user login,php5.4安装dedecms登录后台空白解决办法(session_register函数已废弃)...
  3. 2020笔记本性价比之王_什么笔记本性价比高?2020性价比最高的笔记本电脑
  4. php获取音频的时长,PHP编程获取音频文件时长的方法【基于getid3类】
  5. dataframe修改数据_数据处理进阶pandas入门(一)
  6. java不进入for_为什么阿里巴巴Java开发手册中强制要求不要在foreach循环里进行元素的remove和add操作?...
  7. 计算机应用基础山东省,2019年山东省中等职业学校对口升学考试:计算机文化基础+计算机应用基础模拟试卷...
  8. java websphere mq_如何在java中使用WebSphere MQ?
  9. 剑指offer python实现_剑指Offer第2题详解(附Python、Java代码实现)
  10. mysql 字符转换函数是_MySQL日期和字符串转换函数