moss 2007 定时服务的简化开发和部署
摘要:此定时器,可以动态的加载计时任务的个数,在修改配置加载计时任务后,不用重启moss的定时服务,自动加载修改过的配置文件。
此定时器,可以动态的加载计时任务的个数,在修改配置加载计时任务后,不用重启moss的定时服务,
自动加载修改过的配置文件。

核心类如下:
1
{
18
publicclassTaskConfig:IConfigurationSectionHandler
19

{
20
IConfigurationSectionHandlerMembers#regionIConfigurationSectionHandlerMembers21
publicstaticobjectReadConfig(stringFileName,stringSectionName)
22

{
23
XmlReaderreader=null;
24
try25

{
26
XmlDocumentdoc=newXmlDocument();
27
reader=newXmlTextReader(FileName);
28
doc.Load(reader);
29
XmlNodenode=doc.SelectSingleNode("configuration/"+SectionName);
30
returnReadConfig(node);
31
}32
catch33

{
34
throw;
35
}36
finally37

{
38
if(reader!=null)
39
reader.Close();
40
}41
returnnull;
42
}43
publicstaticobjectReadConfig(System.Xml.XmlNodesection)
44

{
45
List<TaskItem>list=newList<TaskItem>();
46
TaskItemti=null;
47
foreach(System.Xml.XmlNodenodeinsection.ChildNodes)
48

{
49
try50

{
51
ti=newTaskItem();
52
ti.JobName=node.Attributes["JobName"].Value;
53
ti.JobTime=int.Parse(node.Attributes["JobTime"].Value);
54
//ti.Task=(ITask)newSystem.Reflection.Assembly.CreateInstance(node.Attributes["Task"].Value);55
stringstr=node.Attributes["Type"].Value.ToString();
56
ti.Task=(ITask)Type.GetType(str).Assembly.CreateInstance(str.Split(',')[0]);
57
Console.WriteLine("JobName={0},JobTime={1},Type={2}",ti.JobName,ti.JobTime,str);
58
}59
catch(Exceptionee)
60

{
61
EventLogHandle.WriteException(ee);
62
continue;
63
}64
list.Add(ti);
65
}66
returnlist;
67
}68
publicobjectCreate(objectparent,objectconfigContext,System.Xml.XmlNodesection)
69

{
70
returnReadConfig(section);
71
}72
73
#endregion74
}75
publicinterfaceITask
76

{
77
voidExecute(GuidSiteID);
78
}79
publicclassTaskItem
80

{
81
publicstringJobName="";
82
publicstringSiteName="";
83
publicintJobTime=5;
84
publicintCurrentTime=0;
85
publicITaskTask=null;
86
}87
publicclassTask:Microsoft.SharePoint.Administration.SPJobDefinition
88

{
89
publicTask()
90
:base()
91

{
92
ReadConfig();
93
}94
95
publicTask(stringjobName,SPServiceservice,SPServerserver,SPJobLockTypetargetType)
96
:base(jobName,service,server,targetType)
97

{
98
ReadConfig();
99
}100
101
publicTask(stringjobName,SPWebApplicationwebApplication)
102
:base(jobName,webApplication,null,SPJobLockType.ContentDatabase)
103

{
104
this.Title="TaskLogger";
105
ReadConfig();
106
}107
staticHashtableob=newHashtable();
108
staticList<TaskItem>list=newList<TaskItem>();
109
staticGuidFeatureID=newGuid("1F481C17-4FDA-4919-A64A-EAE5C1301B4B");
110
privatestringbasepath=AppDomain.CurrentDomain.BaseDirectory;//@"C:\ProgramFiles\CommonFiles\MicrosoftShared\webserverextensions\12\bin";111
privatestringconfigName="OwsTimer.exe.config";//"Task.dll.config";112
/**////<summary>113
///读取配置信息:
114
///格式:
115
///<Jobs>116
///<JobJobName="JobName"Type=""JobTime="2"SiteName=""/>117
///</Jobs>118
///</summary>
119
privatevoidReadConfig()
120

{
121
list=TaskConfig.ReadConfig(basepath+"\\"+configName,"Jobs")asList<TaskItem>;
122
StartWatcher(basepath,configName,true);
123
}124
staticFileSystemWatcherwatcher=newFileSystemWatcher();
125
[PermissionSet(SecurityAction.Demand,Name="FullTrust")]
126
privatestaticvoidStartWatcher(stringFilepath,stringstrFilter,boolflag)
127

{
128
129
try130

{
131
if(flag==true)
132

{
133
EventLogHandle.WriteEvent(newstring[]
{"启动文件监视器开始……"});
134
watcher.Filter=strFilter;
135
watcher.Path=Filepath;
136
watcher.NotifyFilter=NotifyFilters.LastWrite;
137
watcher.Changed+=newFileSystemEventHandler(OnChanged);
138
EventLogHandle.WriteEvent(newstring[]
{"文件监视器启动成功。"});
139
}140
else141

{
142
EventLogHandle.WriteEvent(newstring[]
{"关闭文件监视器开始……"});
143
watcher.Changed-=newFileSystemEventHandler(OnChanged);
144
EventLogHandle.WriteEvent(newstring[]
{"文件监视器关闭完成"});
145
}146
watcher.EnableRaisingEvents=flag;
147
}148
catch(Exceptionee)
149

{
150
EventLogHandle.WriteException(ee);
151
}152
}153
privatestaticvoidOnChanged(objectsource,FileSystemEventArgse)
154

{
155
System.Threading.Thread.Sleep(5000);
156
lock(ob.SyncRoot)
157

{
158
list.Clear();
159
try160

{
161
list=TaskConfig.ReadConfig(e.FullPath,"Jobs")asList<TaskItem>;
162
}163
catch(Exceptionee)
164

{
165
list=newList<TaskItem>();
166
EventLogHandle.WriteException(ee);
167
}168
}169
}170
/**////<summary>171
///执行多个任务
172
///</summary>173
///<paramname="contentDbId"></param>
174
publicoverridevoidExecute(GuidcontentDbId)
175

{
176
lock(ob.SyncRoot)
177

{
178
foreach(TaskItemtiinlist)
179

{
180
try181

{
182
ti.CurrentTime++;
183
if(ti.CurrentTime==ti.JobTime)
184

{
185
//foreach(SPSitesiteinWebApplication.Sites)
186
//{
187
//foreach(SPFeaturefeainsite.Features)
188
//{
189
//if(fea.Definition.SolutionId==FeatureID&&fea.Definition.Status==SPObjectStatus.Online)
190
//{
191
//try
192
//{
193
//ti.Task.Execute(site.ID);
194
//}
195
//catch(Exceptionee)
196
//{
197
//WriteEvent(site.Url,ee.ToString());
198
//EventLogHandle.WriteException(ee);
199
//}
200
//}
201
//}
202
//}203
ti.Task.Execute(contentDbId);
204
205
}206
}207
catch(Exceptioneee)
208

{
209
WriteEvent(ti.JobName,eee.ToString());
210
EventLogHandle.WriteException(eee);
211
}212
finally213

{
214
if(ti.CurrentTime==ti.JobTime)
215

{
216
ti.CurrentTime=0;
217
}218
}219
}220
}221
/**/////getareferencetothecurrentsitecollection'scontentdatabase
222
//SPWebApplicationwebApplication=this.ParentasSPWebApplication;
223
//SPContentDatabasecontentDb=webApplication.ContentDatabases[contentDbId];224
225
/**/////getareferencetothe"Tasks"listintheRootWebofthefirstsitecollectioninthecontentdatabase
226
//SPListtaskList=contentDb.Sites[0].RootWeb.Lists["Tasks"];227
228
/**/////createanewtask,settheTitletothecurrentday/time,andupdatetheitem
229
//SPListItemnewTask=taskList.Items.Add();
230
//newTask["Title"]=DateTime.Now.ToString();
231
//newTask.Update();
232
//SPSecurity.RunWithElevatedPrivileges(delegate()
233
//{
234
//try
235
//{
236
//using(StreamWritersw=newStreamWriter("C:\\time.txt",false,System.Text.Encoding.UTF8))
237
//{
238
//sw.WriteLine("这是第{0}次写入,当前时间是:{1}",nCount.ToString(),DateTime.Now.ToLongDateString());
239
//}
240
//}
241
//catch
242
//{
243
//}
244
//});245
}246
staticvoidWriteEvent(stringSiteName,stringmsg)
247

{
248
SPSecurity.RunWithElevatedPrivileges(delegate()
249

{
250
try251

{
252
using(StreamWritersw=newStreamWriter("C:\\time.txt",true,System.Text.Encoding.UTF8))
253

{
254
sw.WriteLine("\n时间:{2}\n站点名称:{0}\n日志信息:{1}",SiteName,msg,DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss"));
255
}256
}257
catch258

{
259
}260
});
261
}262
}263
264
classEventLogHandle
265

{
266
staticEventLog_eventLog=null;
267
staticEventLogHandle()
268

{
269
_eventLog=newEventLog("Application",".","SPTaskProvider");
270
}271
publicstaticvoidWriteException(Exceptione)
272

{
273
_eventLog.WriteEntry(string.Concat(e.Message,Environment.NewLine,Environment.NewLine,e.StackTrace),EventLogEntryType.Error);
274
}275
publicstaticvoidWriteEvent(string[]strArray)
276

{
277
_eventLog.WriteEntry(string.Concat(strArray),EventLogEntryType.Information);
278
}279
publicstaticvoidWriteWarn(string[]strArray)
280

{
281
_eventLog.WriteEntry(string.Concat(strArray),EventLogEntryType.Warning);
282
}283
}284
}285
调试用控制台源
码:
{
13
classProgram
14

{
15
staticList<TaskItem>list=newList<TaskItem>();
16
staticTasktask=null;
17
staticvoidMain(string[]args)
18

{
19
Console.ReadKey();
20
System.Timers.Timertime=null;
21
try22

{
23
task=newTask();
24
time=newSystem.Timers.Timer();
25
time.Interval=10000;
26
time.Enabled=true;
27
time.Elapsed+=newSystem.Timers.ElapsedEventHandler(time_Elapsed);
28
}29
catch(Exceptionee)
30

{
31
Console.Write(ee.ToString());
32
}33
Console.ReadKey();
34
time.Enabled=false;
35
}36
37
staticvoidtime_Elapsed(objectsender,System.Timers.ElapsedEventArgse)
38

{
39
if(task!=null)
40
task.Execute(Guid.Empty);
41
}42
}43
publicclassTask1:ITask
44

{
45
ITaskMembers#regionITaskMembers46
47
publicvoidExecute(GuidSiteID)
48

{
49
Console.WriteLine("Task1:SiteID="+SiteID.ToString());
50
}51
52
#endregion53
}54
publicclassTask3:ITask
55

{
56
ITaskMembers#regionITaskMembers57
58
publicvoidExecute(GuidSiteID)
59

{
60
//thrownewException("Themethodoroperationisnotimplemented.");61
Console.WriteLine("Task3:SiteID="+SiteID.ToString());
62
}63
64
#endregion65
}66
publicclassTask2:ITask
67

{
68
ITaskMembers#regionITaskMembers69
70
publicvoidExecute(GuidSiteID)
71

{
72
Console.WriteLine("Task2:SiteID="+SiteID.ToString());
73
}74
75
#endregion76
}77
}78
Code
1
<?xmlversion="1.0"encoding="utf-8"?>2
<configuration>3
<configSections>4
<sectionname="Jobs"type="ConsoleApplication1.TaskConfig,ConsoleApplication1"/>5
</configSections>6
<Jobs>7
<JobJobName="JobName1"JobTime="1"Type="ConsoleApplication1.Task1,ConsoleApplication1"></Job>8
<JobJobName="JobName2"JobTime="2"Type="ConsoleApplication1.Task2,ConsoleApplication1"></Job>9
<JobJobName="JobName3"JobTime="3"Type="ConsoleApplication1.Task3,ConsoleApplication1"></Job>10
</Jobs>11
</configuration> 完成
免责声明:文章转载自《moss 2007 定时服务的简化开发和部署》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
上篇WebApi管理和性能测试工具WebApiBenchmarks在家赚钱,威客网站的使用方法 CSDN项目频道、SXSOFT、任务中国、猪八戒四个网站的线上交易 三种交易模式(1)悬赏模式(2)招标模式(3)直接交易模式下篇
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=