moss 2007 定时服务的简化开发和部署

本文介绍了一种能够动态加载计时任务的定时器实现方案,该方案能够在不重启服务的情况下自动加载更新后的配置文件,支持任务数量的动态调整。
此定时器,可以动态的加载计时任务的个数,在修改配置加载计时任务后,不用重启moss的定时服务,
自动加载修改过的配置文件。


核心类如下:
  1using System;
  2using System.Collections;
  3using System.Collections.Generic;
  4using System.Text;
  5using Microsoft.SharePoint.Administration;
  6using Microsoft.SharePoint;
  7using System.IO;
  8using System.Configuration;
  9
 10using System.Security.Permissions;
 11using System.Xml;
 12using System.Diagnostics;
 13
 14using System.Runtime.InteropServices;
 15using System.Runtime.CompilerServices;
 16namespace TaskJob
 17{
 18    public class TaskConfig : IConfigurationSectionHandler
 19    {
 20        IConfigurationSectionHandler Members#region IConfigurationSectionHandler Members
 21        public static object ReadConfig(string FileName, string SectionName)
 22        {
 23            XmlReader reader = null;
 24            try
 25            {
 26                XmlDocument doc = new XmlDocument();
 27                reader = new XmlTextReader(FileName);
 28                doc.Load(reader);
 29                XmlNode node = doc.SelectSingleNode("configuration/" + SectionName);
 30                return ReadConfig(node);
 31            }

 32            catch
 33            {
 34                throw;
 35            }

 36            finally
 37            {
 38                if (reader != null)
 39                    reader.Close();
 40            }

 41            return null;
 42        }

 43        public static object ReadConfig(System.Xml.XmlNode section)
 44        {
 45            List<TaskItem> list = new List<TaskItem>();
 46            TaskItem ti = null;
 47            foreach (System.Xml.XmlNode node in section.ChildNodes)
 48            {
 49                try
 50                {
 51                    ti = new TaskItem();
 52                    ti.JobName = node.Attributes["JobName"].Value;
 53                    ti.JobTime = int.Parse(node.Attributes["JobTime"].Value);
 54                    //ti.Task = (ITask)new System.Reflection.Assembly.CreateInstance(node.Attributes["Task"].Value);
 55                    string str = 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(Exception ee)
 60                {
 61                    EventLogHandle.WriteException(ee);
 62                    continue;
 63                }

 64                list.Add(ti);
 65            }

 66            return list;
 67        }

 68        public object Create(object parent, object configContext, System.Xml.XmlNode section)
 69        {
 70            return ReadConfig(section);
 71        }

 72
 73        #endregion

 74    }

 75    public interface ITask
 76    {
 77        void Execute(Guid SiteID);
 78    }

 79    public class TaskItem
 80    {
 81        public string JobName = "";
 82        public string SiteName = "";
 83        public int JobTime = 5;
 84        public int CurrentTime = 0;
 85        public ITask Task = null;
 86    }

 87    public class Task : Microsoft.SharePoint.Administration.SPJobDefinition
 88    {
 89        public Task()
 90            : base()
 91        {
 92            ReadConfig();
 93        }

 94
 95        public Task(string jobName, SPService service, SPServer server, SPJobLockType targetType)
 96            : base(jobName, service, server, targetType)
 97        {
 98            ReadConfig();
 99        }

100
101        public Task(string jobName, SPWebApplication webApplication)
102            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
103        {
104            this.Title = "Task Logger";
105            ReadConfig();
106        }

107        static Hashtable  ob = new Hashtable();
108        static List<TaskItem> list = new List<TaskItem>();
109        static Guid FeatureID = new Guid("1F481C17-4FDA-4919-A64A-EAE5C1301B4B");
110        private string basepath =AppDomain.CurrentDomain.BaseDirectory; //@"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\bin";
111        private string configName = "OwsTimer.exe.config";//"Task.dll.config";
112        /**//// <summary>
113        /// 读取配置信息:
114        /// 格式:
115        /// <Jobs>
116        ///<Job JobName="JobName" Type="" JobTime="2" SiteName=""/>
117        ///</Jobs>
118        /// </summary>

119        private void ReadConfig()
120        {
121            list = TaskConfig.ReadConfig(basepath + "\\"+configName, "Jobs"as List<TaskItem>;
122            StartWatcher(basepath, configName, true);            
123        }

124        static FileSystemWatcher watcher = new FileSystemWatcher();
125        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
126        private static void StartWatcher(string Filepath, string strFilter, bool flag)
127        {
128
129            try
130            {
131                if (flag == true)
132                {
133                    EventLogHandle.WriteEvent(new string[] "启动文件监视器开始……" });
134                    watcher.Filter = strFilter;
135                    watcher.Path = Filepath;
136                    watcher.NotifyFilter = NotifyFilters.LastWrite;
137                    watcher.Changed += new FileSystemEventHandler(OnChanged);
138                    EventLogHandle.WriteEvent(new string[] "文件监视器启动成功。" });
139                }

140                else
141                {
142                    EventLogHandle.WriteEvent(new string[] "关闭文件监视器开始……" });
143                    watcher.Changed -= new FileSystemEventHandler(OnChanged);
144                    EventLogHandle.WriteEvent(new string[] "文件监视器关闭完成" });
145                }

146                watcher.EnableRaisingEvents = flag;
147            }

148            catch (Exception ee)
149            {
150                EventLogHandle.WriteException(ee);
151            }

152        }

153        private static void OnChanged(object source, FileSystemEventArgs e)
154        {
155            System.Threading.Thread.Sleep(5000);
156            lock (ob.SyncRoot)
157            {
158                list.Clear();
159                try
160                {
161                    list = TaskConfig.ReadConfig(e.FullPath, "Jobs"as List<TaskItem>;
162                }

163                catch (Exception ee)
164                {
165                    list = new List<TaskItem>();
166                    EventLogHandle.WriteException(ee);
167                }

168            }

169        }
     
170        /**//// <summary>
171        /// 执行多个任务
172        /// </summary>
173        /// <param name="contentDbId"></param>

174        public override void Execute(Guid contentDbId)
175        {
176            lock (ob.SyncRoot)
177            {
178                foreach (TaskItem ti in list)
179                {
180                    try
181                    {
182                        ti.CurrentTime++;
183                        if (ti.CurrentTime == ti.JobTime)
184                        {
185                            //foreach (SPSite site in WebApplication.Sites)
186                            //{
187                            //    foreach (SPFeature fea in site.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(Exception ee)
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 (Exception eee)
208                    {
209                        WriteEvent(ti.JobName, eee.ToString());
210                        EventLogHandle.WriteException(eee);
211                    }

212                    finally
213                    {
214                        if (ti.CurrentTime == ti.JobTime)
215                        {
216                            ti.CurrentTime = 0;
217                        }

218                    }

219                }

220            }

221            /**///// get a reference to the current site collection's content database
222            //SPWebApplication webApplication = this.Parent as SPWebApplication;
223            //SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
224
225            /**///// get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
226            //SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];
227
228            /**///// create a new task, set the Title to the current day/time, and update the item
229            //SPListItem newTask = taskList.Items.Add();
230            //newTask["Title"] = DateTime.Now.ToString();
231            //newTask.Update();
232            //SPSecurity.RunWithElevatedPrivileges(delegate()
233            //{
234            //    try
235            //    {
236            //        using (StreamWriter sw = new StreamWriter("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        static void WriteEvent(string SiteName, string msg)
247        {
248           SPSecurity.RunWithElevatedPrivileges(delegate()
249           {
250               try
251               {
252                   using (StreamWriter sw = new StreamWriter("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-dd HH:mm:ss"));
255                   }

256               }

257               catch
258               {
259               }

260           }
);
261        }

262    }

263
264    class EventLogHandle
265    {
266        static EventLog _eventLog = null;
267        static EventLogHandle()
268        {
269            _eventLog = new EventLog("Application"".""SPTaskProvider");
270        }

271        public static void WriteException(Exception e)
272        {
273            _eventLog.WriteEntry(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace), EventLogEntryType.Error);
274        }

275        public static void WriteEvent(string [] strArray)
276        {
277            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Information);            
278        }

279        public static void WriteWarn(string[] strArray)
280        {
281            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Warning);
282        }

283    }

284}

285

调试用控制台源
码:
Code
 1using System;
 2using System.Collections.Generic;
 3using System.Collections;
 4using System.Text;
 5using System.Configuration;
 6using System.IO;
 7using System.Security.Permissions;
 8using System.Xml;
 9using TaskJob;
10
11namespace ConsoleApplication1
12{
13    class Program
14    {
15        static List<TaskItem> list = new List<TaskItem>();
16        static Task task = null;
17        static void Main(string[] args)
18        {
19            Console.ReadKey();
20            System.Timers.Timer time = null;
21            try
22            {
23                task = new Task();
24                time = new System.Timers.Timer();
25                time.Interval = 10000;
26                time.Enabled = true;
27                time.Elapsed += new System.Timers.ElapsedEventHandler(time_Elapsed);
28            }

29            catch (Exception ee)
30            {
31                Console.Write(ee.ToString());
32            }

33            Console.ReadKey();
34            time.Enabled = false;
35        }

36
37        static void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
38        {
39            if (task != null)
40                task.Execute(Guid.Empty);
41        }

42    }

43    public class Task1:ITask
44    {
45        ITask Members#region ITask Members
46
47        public void Execute(Guid SiteID)
48        {
49            Console.WriteLine("Task1:SiteID=" + SiteID.ToString());
50        }

51
52        #endregion

53    }

54    public class Task3 : ITask
55    {
56        ITask Members#region ITask Members
57
58        public void Execute(Guid SiteID)
59        {
60            //throw new Exception("The method or operation is not implemented.");
61            Console.WriteLine("Task3:SiteID=" + SiteID.ToString());
62        }

63
64        #endregion

65    }

66    public class Task2 : ITask
67    {
68        ITask Members#region ITask Members
69
70        public void Execute(Guid SiteID)
71        {
72            Console.WriteLine("Task2:SiteID=" + SiteID.ToString());
73        }

74
75        #endregion

76    }
   
77}

78


Code
 1<?xml version="1.0" encoding="utf-8" ?>
 2<configuration>
 3  <configSections>
 4    <section name="Jobs" type="ConsoleApplication1.TaskConfig,ConsoleApplication1"/>
 5  </configSections> 
 6  <Jobs>
 7    <Job JobName="JobName1" JobTime="1" Type="ConsoleApplication1.Task1,ConsoleApplication1"></Job>
 8    <Job JobName="JobName2" JobTime="2" Type="ConsoleApplication1.Task2,ConsoleApplication1"></Job>
 9    <Job JobName="JobName3" JobTime="3" Type="ConsoleApplication1.Task3,ConsoleApplication1"></Job>
10  </Jobs>   
11</configuration>

完成

转载于:https://www.cnblogs.com/LifelongLearning/archive/2008/06/03/1212778.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值