Logo

SharePoint 开发学习——Timer Job

photo

2024年01月22日

SharePoint 开发学习——Timer Job

作者:spring yang

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

 

概要

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

开发设计

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

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

?
1
2
3
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;

TaskLoggerJob设计代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 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时我们调用这个构造方法:

?
1
2
3
4
5
6
7
8
9
10
/// <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具体要做的事性我们实现这个方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/// <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 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的代码设计,首先引用:

?
1
2
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

而后代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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方件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/// <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();
        }
    }
}
?
1
 
?
1
 
?
1
卸载这个Job的方法如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/// <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的执行时间可以按分、时、天、月、年来执行可以进行如下定义,分、时、天。概据你的需要来执行。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/// <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/

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
所有附件
本文为原创文章,请注意保留出处!

热门文章

西游记之大圣归来 《西游记之大圣归来》是根据中国传统神话故事《西游记》进行拓展和演绎的3D动画电影。由横店影视、天空之城、燕城十月与微影时代作为出品方,高路动画、恭梓兄弟、世纪长龙、山东影视、东台龙行盛世、淮安西游产业与永康壹禾作为联合出品方出品,田晓鹏执导,张磊、林子杰、刘九容和童自荣等联袂配音。影片讲述了已于五行山下寂寞沉潜五百年的孙悟空被儿时的唐僧——俗名江流儿的小和尚误打误撞地解除了封印,在相互陪伴的冒险之旅中找回初心,完成自我救赎的故事。 作者:Pastore Antonio
1448 浏览量
常用的Centos操作Shell命令 玩WordPress的时候经常会接触到一些常用的命令,老是忘记……人年纪大了就是不给力啊。浏览量:...常用的Centos操作Shell命令 作者:Pastore Antonio
1387 浏览量
ffmpeg+srs 实现直播流 这篇文章是我在做直播流的时候收集的所有素材,没有太多的整理,都放到了脑袋里面了,之后有时间了再整理成...ffmpeg+srs实现直播流 作者:Pastore Antonio
1387 浏览量
项目十大管理和五大过程 PMBOK五大过程组是什么?PMBOK五大过程组是:启动过程、规划过程、执行过程、监...项目十大管理和五大过程 作者:Pastore Antonio
1363 浏览量
[ Office 365 开发系列 ] 身份认证 前言本文完全原创,转载请说明出处,希望对大家有用。通常我们在开发一个应用时,需要考虑用户身份认证...[Office365开发系列]身份认证 作者:Pastore Antonio
1357 浏览量