moss 2007 定时服务的简化开发和部署
此定时器,可以动态的加载计时任务的个数,在修改配置加载计时任务后,不用重启moss的定时服务,
自动加载修改过的配置文件。
![]()
核心类如下:
调试用控制台源
码:![]() Code
Code
![]() Code
Code
完成
    
自动加载修改过的配置文件。

核心类如下:
  1![]() using System;
using System;
2![]() using System.Collections;
using System.Collections;
3![]() using System.Collections.Generic;
using System.Collections.Generic;
4![]() using System.Text;
using System.Text;
5![]() using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration;
6![]() using Microsoft.SharePoint;
using Microsoft.SharePoint;
7![]() using System.IO;
using System.IO;
8![]() using System.Configuration;
using System.Configuration;
9![]()
10![]() using System.Security.Permissions;
using System.Security.Permissions;
11![]() using System.Xml;
using System.Xml;
12![]() using System.Diagnostics;
using System.Diagnostics;
13![]()
14![]() using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
15![]() using System.Runtime.CompilerServices;
using System.Runtime.CompilerServices;
16![]() namespace TaskJob
namespace TaskJob
17![]() {
{
18![]() public class TaskConfig : IConfigurationSectionHandler
    public class TaskConfig : IConfigurationSectionHandler
19![]() {
    {
20![]() IConfigurationSectionHandler Members
        IConfigurationSectionHandler Members
74![]() }
    }
75![]() public interface ITask
    public interface ITask
76![]() {
    {
77![]() void Execute(Guid SiteID);
        void Execute(Guid SiteID);
78![]() }
    }
79![]() public class TaskItem
    public class TaskItem
80![]() {
    {
81![]() public string JobName = "";
        public string JobName = "";
82![]() public string SiteName = "";
        public string SiteName = "";
83![]() public int JobTime = 5;
        public int JobTime = 5;
84![]() public int CurrentTime = 0;
        public int CurrentTime = 0;
85![]() public ITask Task = null;
        public ITask Task = null;
86![]() }
    }
87![]() public class Task : Microsoft.SharePoint.Administration.SPJobDefinition
    public class Task : Microsoft.SharePoint.Administration.SPJobDefinition
88![]() {
    {
89![]() public Task()
        public Task()
90![]() : base()
            : base()
91![]() {
        {
92![]() ReadConfig();
            ReadConfig();
93![]() }
        }
94![]()
95![]() public Task(string jobName, SPService service, SPServer server, SPJobLockType targetType)
        public Task(string jobName, SPService service, SPServer server, SPJobLockType targetType)
96![]() : base(jobName, service, server, targetType)
            : base(jobName, service, server, targetType)
97![]() {
        {
98![]() ReadConfig();
            ReadConfig();
99![]() }
        }
100![]()
101![]() public Task(string jobName, SPWebApplication webApplication)
        public Task(string jobName, SPWebApplication webApplication)
102![]() : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
103![]() {
        {
104![]() this.Title = "Task Logger";
            this.Title = "Task Logger";
105![]() ReadConfig();
            ReadConfig();
106![]() }
        }
107![]() static Hashtable  ob = new Hashtable();
        static Hashtable  ob = new Hashtable();
108![]() static List<TaskItem> list = new List<TaskItem>();
        static List<TaskItem> list = new List<TaskItem>();
109![]() static Guid FeatureID = new Guid("1F481C17-4FDA-4919-A64A-EAE5C1301B4B");
        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";
        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";
        private string configName = "OwsTimer.exe.config";//"Task.dll.config";
112![]() /// <summary>
        /// <summary>
113![]() /// 读取配置信息:
        /// 读取配置信息:
114![]() /// 格式:
        /// 格式:
115![]() /// <Jobs>
        /// <Jobs>
116![]() ///<Job JobName="JobName" Type="" JobTime="2" SiteName=""/>
        ///<Job JobName="JobName" Type="" JobTime="2" SiteName=""/>
117![]() ///</Jobs>
        ///</Jobs>
118![]() /// </summary>
        /// </summary>
119![]() private void ReadConfig()
        private void ReadConfig()
120![]() {
        {
121![]() list = TaskConfig.ReadConfig(basepath + "\\"+configName, "Jobs") as List<TaskItem>;
            list = TaskConfig.ReadConfig(basepath + "\\"+configName, "Jobs") as List<TaskItem>;
122![]() StartWatcher(basepath, configName, true);
            StartWatcher(basepath, configName, true);            
123![]() }
        }
124![]() static FileSystemWatcher watcher = new FileSystemWatcher();
        static FileSystemWatcher watcher = new FileSystemWatcher();
125![]() [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
126![]() private static void StartWatcher(string Filepath, string strFilter, bool flag)
        private static void StartWatcher(string Filepath, string strFilter, bool flag)
127![]() {
        {
128![]()
129![]() try
            try
130![]() {
            {
131![]() if (flag == true)
                if (flag == true)
132![]() {
                {
133![]() EventLogHandle.WriteEvent(new string[] { "启动文件监视器开始……" });
                    EventLogHandle.WriteEvent(new string[] { "启动文件监视器开始……" });
134![]() watcher.Filter = strFilter;
                    watcher.Filter = strFilter;
135![]() watcher.Path = Filepath;
                    watcher.Path = Filepath;
136![]() watcher.NotifyFilter = NotifyFilters.LastWrite;
                    watcher.NotifyFilter = NotifyFilters.LastWrite;
137![]() watcher.Changed += new FileSystemEventHandler(OnChanged);
                    watcher.Changed += new FileSystemEventHandler(OnChanged);
138![]() EventLogHandle.WriteEvent(new string[] { "文件监视器启动成功。" });
                    EventLogHandle.WriteEvent(new string[] { "文件监视器启动成功。" });
139![]() }
                }
140![]() else
                else
141![]() {
                {
142![]() EventLogHandle.WriteEvent(new string[] { "关闭文件监视器开始……" });
                    EventLogHandle.WriteEvent(new string[] { "关闭文件监视器开始……" });
143![]() watcher.Changed -= new FileSystemEventHandler(OnChanged);
                    watcher.Changed -= new FileSystemEventHandler(OnChanged);
144![]() EventLogHandle.WriteEvent(new string[] { "文件监视器关闭完成" });
                    EventLogHandle.WriteEvent(new string[] { "文件监视器关闭完成" });
145![]() }
                }
146![]() watcher.EnableRaisingEvents = flag;
                watcher.EnableRaisingEvents = flag;
147![]() }
            }
148![]() catch (Exception ee)
            catch (Exception ee)
149![]() {
            {
150![]() EventLogHandle.WriteException(ee);
                EventLogHandle.WriteException(ee);
151![]() }
            }
152![]() }
        }
153![]() private static void OnChanged(object source, FileSystemEventArgs e)
        private static void OnChanged(object source, FileSystemEventArgs e)
154![]() {
        {
155![]() System.Threading.Thread.Sleep(5000);
            System.Threading.Thread.Sleep(5000);
156![]() lock (ob.SyncRoot)
            lock (ob.SyncRoot)
157![]() {
            {
158![]() list.Clear();
                list.Clear();
159![]() try
                try
160![]() {
                {
161![]() list = TaskConfig.ReadConfig(e.FullPath, "Jobs") as List<TaskItem>;
                    list = TaskConfig.ReadConfig(e.FullPath, "Jobs") as List<TaskItem>;
162![]() }
                }
163![]() catch (Exception ee)
                catch (Exception ee)
164![]() {
                {
165![]() list = new List<TaskItem>();
                    list = new List<TaskItem>();
166![]() EventLogHandle.WriteException(ee);
                    EventLogHandle.WriteException(ee);
167![]() }
                }
168![]() }
            }
169![]() }
        }     
170![]() /// <summary>
        /// <summary>
171![]() /// 执行多个任务
        /// 执行多个任务
172![]() /// </summary>
        /// </summary>
173![]() /// <param name="contentDbId"></param>
        /// <param name="contentDbId"></param>
174![]() public override void Execute(Guid contentDbId)
        public override void Execute(Guid contentDbId)
175![]() {
        {
176![]() lock (ob.SyncRoot)
            lock (ob.SyncRoot)
177![]() {
            {
178![]() foreach (TaskItem ti in list)
                foreach (TaskItem ti in list)
179![]() {
                {
180![]() try
                    try
181![]() {
                    {
182![]() ti.CurrentTime++;
                        ti.CurrentTime++;
183![]() if (ti.CurrentTime == ti.JobTime)
                        if (ti.CurrentTime == ti.JobTime)
184![]() {
                        {
185![]() //foreach (SPSite site in WebApplication.Sites)
                            //foreach (SPSite site in WebApplication.Sites)
186![]() //{
                            //{
187![]() //    foreach (SPFeature fea in site.Features)
                            //    foreach (SPFeature fea in site.Features)
188![]() //    {
                            //    {
189![]() //        if (fea.Definition.SolutionId == FeatureID && fea.Definition.Status == SPObjectStatus.Online)
                            //        if (fea.Definition.SolutionId == FeatureID && fea.Definition.Status == SPObjectStatus.Online)
190![]() //        {
                            //        {
191![]() //            try
                            //            try
192![]() //            {
                            //            {
193![]() //                ti.Task.Execute(site.ID);
                            //                ti.Task.Execute(site.ID);
194![]() //            }
                            //            }
195![]() //            catch(Exception ee)
                            //            catch(Exception ee)
196![]() //            {
                            //            {
197![]() //                WriteEvent(site.Url, ee.ToString());
                            //                WriteEvent(site.Url, ee.ToString());
198![]() //                EventLogHandle.WriteException(ee);
                            //                EventLogHandle.WriteException(ee);
199![]() //            }
                            //            }
200![]() //        }
                            //        }
201![]() //    }
                            //    }
202![]() //}
                            //}
203![]() ti.Task.Execute(contentDbId);
                            ti.Task.Execute(contentDbId);
204![]() 
                            
205![]() }
                        }
206![]() }
                    }
207![]() catch (Exception eee)
                    catch (Exception eee)
208![]() {
                    {
209![]() WriteEvent(ti.JobName, eee.ToString());
                        WriteEvent(ti.JobName, eee.ToString());
210![]() EventLogHandle.WriteException(eee);
                        EventLogHandle.WriteException(eee);
211![]() }
                    }
212![]() finally
                    finally
213![]() {
                    {
214![]() if (ti.CurrentTime == ti.JobTime)
                        if (ti.CurrentTime == ti.JobTime)
215![]() {
                        {
216![]() ti.CurrentTime = 0;
                            ti.CurrentTime = 0;
217![]() }
                        }
218![]() }
                    }
219![]() }
                }
220![]() }
            }
221![]() //// get a reference to the current site collection's content database
            //// get a reference to the current site collection's content database
222![]() //SPWebApplication webApplication = this.Parent as SPWebApplication;
            //SPWebApplication webApplication = this.Parent as SPWebApplication;
223![]() //SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
            //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
            //// 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"];
            //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
            //// create a new task, set the Title to the current day/time, and update the item
229![]() //SPListItem newTask = taskList.Items.Add();
            //SPListItem newTask = taskList.Items.Add();
230![]() //newTask["Title"] = DateTime.Now.ToString();
            //newTask["Title"] = DateTime.Now.ToString();
231![]() //newTask.Update();
            //newTask.Update();
232![]() //SPSecurity.RunWithElevatedPrivileges(delegate()
            //SPSecurity.RunWithElevatedPrivileges(delegate()
233![]() //{
            //{
234![]() //    try
            //    try
235![]() //    {
            //    {
236![]() //        using (StreamWriter sw = new StreamWriter("C:\\time.txt", false, System.Text.Encoding.UTF8))
            //        using (StreamWriter sw = new StreamWriter("C:\\time.txt", false, System.Text.Encoding.UTF8))
237![]() //        {
            //        {
238![]() //            sw.WriteLine("这是第{0}次写入,当前时间是:{1}", nCount.ToString(), DateTime.Now.ToLongDateString());
            //            sw.WriteLine("这是第{0}次写入,当前时间是:{1}", nCount.ToString(), DateTime.Now.ToLongDateString());
239![]() //        }
            //        }
240![]() //    }
            //    }
241![]() //    catch
            //    catch
242![]() //    {
            //    {
243![]() //    }
            //    }
244![]() //});
            //});
245![]() }
        }
246![]() static void WriteEvent(string SiteName, string msg)
        static void WriteEvent(string SiteName, string msg)
247![]() {
        {
248![]() SPSecurity.RunWithElevatedPrivileges(delegate()
           SPSecurity.RunWithElevatedPrivileges(delegate()
249![]() {
           {
250![]() try
               try
251![]() {
               {
252![]() using (StreamWriter sw = new StreamWriter("C:\\time.txt", true, System.Text.Encoding.UTF8))
                   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"));
                       sw.WriteLine("\n时间:{2}\n站点名称:{0}\n日志信息:{1}", SiteName, msg,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
255![]() }
                   }
256![]() }
               }
257![]() catch
               catch
258![]() {
               {
259![]() }
               }
260![]() });
           });
261![]() }
        }
262![]() }
    }
263![]()
264![]() class EventLogHandle
    class EventLogHandle
265![]() {
    {
266![]() static EventLog _eventLog = null;
        static EventLog _eventLog = null;
267![]() static EventLogHandle()
        static EventLogHandle()
268![]() {
        {
269![]() _eventLog = new EventLog("Application", ".", "SPTaskProvider");
            _eventLog = new EventLog("Application", ".", "SPTaskProvider");
270![]() }
        }
271![]() public static void WriteException(Exception e)
        public static void WriteException(Exception e)
272![]() {
        {
273![]() _eventLog.WriteEntry(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace), EventLogEntryType.Error);
            _eventLog.WriteEntry(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace), EventLogEntryType.Error);
274![]() }
        }
275![]() public static void WriteEvent(string [] strArray)
        public static void WriteEvent(string [] strArray)
276![]() {
        {
277![]() _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Information);
            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Information);            
278![]() }
        }
279![]() public static void WriteWarn(string[] strArray)
        public static void WriteWarn(string[] strArray)
280![]() {
        {
281![]() _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Warning);
            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Warning);
282![]() }
        }
283![]() }
    }
284![]() }
}
285![]()
 using System;
using System;2
 using System.Collections;
using System.Collections;3
 using System.Collections.Generic;
using System.Collections.Generic;4
 using System.Text;
using System.Text;5
 using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration;6
 using Microsoft.SharePoint;
using Microsoft.SharePoint;7
 using System.IO;
using System.IO;8
 using System.Configuration;
using System.Configuration;9

10
 using System.Security.Permissions;
using System.Security.Permissions;11
 using System.Xml;
using System.Xml;12
 using System.Diagnostics;
using System.Diagnostics;13

14
 using System.Runtime.InteropServices;
using System.Runtime.InteropServices;15
 using System.Runtime.CompilerServices;
using System.Runtime.CompilerServices;16
 namespace TaskJob
namespace TaskJob17
 {
{18
 public class TaskConfig : IConfigurationSectionHandler
    public class TaskConfig : IConfigurationSectionHandler19
 {
    {20
 IConfigurationSectionHandler Members
        IConfigurationSectionHandler Members74
 }
    }75
 public interface ITask
    public interface ITask76
 {
    {77
 void Execute(Guid SiteID);
        void Execute(Guid SiteID);78
 }
    }79
 public class TaskItem
    public class TaskItem80
 {
    {81
 public string JobName = "";
        public string JobName = "";82
 public string SiteName = "";
        public string SiteName = "";83
 public int JobTime = 5;
        public int JobTime = 5;84
 public int CurrentTime = 0;
        public int CurrentTime = 0;85
 public ITask Task = null;
        public ITask Task = null;86
 }
    }87
 public class Task : Microsoft.SharePoint.Administration.SPJobDefinition
    public class Task : Microsoft.SharePoint.Administration.SPJobDefinition88
 {
    {89
 public Task()
        public Task()90
 : base()
            : base()91
 {
        {92
 ReadConfig();
            ReadConfig();93
 }
        }94

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

101
 public Task(string jobName, SPWebApplication webApplication)
        public Task(string jobName, SPWebApplication webApplication)102
 : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)103
 {
        {104
 this.Title = "Task Logger";
            this.Title = "Task Logger";105
 ReadConfig();
            ReadConfig();106
 }
        }107
 static Hashtable  ob = new Hashtable();
        static Hashtable  ob = new Hashtable();108
 static List<TaskItem> list = new List<TaskItem>();
        static List<TaskItem> list = new List<TaskItem>();109
 static Guid FeatureID = new Guid("1F481C17-4FDA-4919-A64A-EAE5C1301B4B");
        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";
        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";
        private string configName = "OwsTimer.exe.config";//"Task.dll.config";112
 /// <summary>
        /// <summary>113
 /// 读取配置信息:
        /// 读取配置信息:114
 /// 格式:
        /// 格式:115
 /// <Jobs>
        /// <Jobs>116
 ///<Job JobName="JobName" Type="" JobTime="2" SiteName=""/>
        ///<Job JobName="JobName" Type="" JobTime="2" SiteName=""/>117
 ///</Jobs>
        ///</Jobs>118
 /// </summary>
        /// </summary>119
 private void ReadConfig()
        private void ReadConfig()120
 {
        {121
 list = TaskConfig.ReadConfig(basepath + "\\"+configName, "Jobs") as List<TaskItem>;
            list = TaskConfig.ReadConfig(basepath + "\\"+configName, "Jobs") as List<TaskItem>;122
 StartWatcher(basepath, configName, true);
            StartWatcher(basepath, configName, true);            123
 }
        }124
 static FileSystemWatcher watcher = new FileSystemWatcher();
        static FileSystemWatcher watcher = new FileSystemWatcher();125
 [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]126
 private static void StartWatcher(string Filepath, string strFilter, bool flag)
        private static void StartWatcher(string Filepath, string strFilter, bool flag)127
 {
        {128

129
 try
            try130
 {
            {131
 if (flag == true)
                if (flag == true)132
 {
                {133
 EventLogHandle.WriteEvent(new string[] { "启动文件监视器开始……" });
                    EventLogHandle.WriteEvent(new string[] { "启动文件监视器开始……" });134
 watcher.Filter = strFilter;
                    watcher.Filter = strFilter;135
 watcher.Path = Filepath;
                    watcher.Path = Filepath;136
 watcher.NotifyFilter = NotifyFilters.LastWrite;
                    watcher.NotifyFilter = NotifyFilters.LastWrite;137
 watcher.Changed += new FileSystemEventHandler(OnChanged);
                    watcher.Changed += new FileSystemEventHandler(OnChanged);138
 EventLogHandle.WriteEvent(new string[] { "文件监视器启动成功。" });
                    EventLogHandle.WriteEvent(new string[] { "文件监视器启动成功。" });139
 }
                }140
 else
                else141
 {
                {142
 EventLogHandle.WriteEvent(new string[] { "关闭文件监视器开始……" });
                    EventLogHandle.WriteEvent(new string[] { "关闭文件监视器开始……" });143
 watcher.Changed -= new FileSystemEventHandler(OnChanged);
                    watcher.Changed -= new FileSystemEventHandler(OnChanged);144
 EventLogHandle.WriteEvent(new string[] { "文件监视器关闭完成" });
                    EventLogHandle.WriteEvent(new string[] { "文件监视器关闭完成" });145
 }
                }146
 watcher.EnableRaisingEvents = flag;
                watcher.EnableRaisingEvents = flag;147
 }
            }148
 catch (Exception ee)
            catch (Exception ee)149
 {
            {150
 EventLogHandle.WriteException(ee);
                EventLogHandle.WriteException(ee);151
 }
            }152
 }
        }153
 private static void OnChanged(object source, FileSystemEventArgs e)
        private static void OnChanged(object source, FileSystemEventArgs e)154
 {
        {155
 System.Threading.Thread.Sleep(5000);
            System.Threading.Thread.Sleep(5000);156
 lock (ob.SyncRoot)
            lock (ob.SyncRoot)157
 {
            {158
 list.Clear();
                list.Clear();159
 try
                try160
 {
                {161
 list = TaskConfig.ReadConfig(e.FullPath, "Jobs") as List<TaskItem>;
                    list = TaskConfig.ReadConfig(e.FullPath, "Jobs") as List<TaskItem>;162
 }
                }163
 catch (Exception ee)
                catch (Exception ee)164
 {
                {165
 list = new List<TaskItem>();
                    list = new List<TaskItem>();166
 EventLogHandle.WriteException(ee);
                    EventLogHandle.WriteException(ee);167
 }
                }168
 }
            }169
 }
        }     170
 /// <summary>
        /// <summary>171
 /// 执行多个任务
        /// 执行多个任务172
 /// </summary>
        /// </summary>173
 /// <param name="contentDbId"></param>
        /// <param name="contentDbId"></param>174
 public override void Execute(Guid contentDbId)
        public override void Execute(Guid contentDbId)175
 {
        {176
 lock (ob.SyncRoot)
            lock (ob.SyncRoot)177
 {
            {178
 foreach (TaskItem ti in list)
                foreach (TaskItem ti in list)179
 {
                {180
 try
                    try181
 {
                    {182
 ti.CurrentTime++;
                        ti.CurrentTime++;183
 if (ti.CurrentTime == ti.JobTime)
                        if (ti.CurrentTime == ti.JobTime)184
 {
                        {185
 //foreach (SPSite site in WebApplication.Sites)
                            //foreach (SPSite site in WebApplication.Sites)186
 //{
                            //{187
 //    foreach (SPFeature fea in site.Features)
                            //    foreach (SPFeature fea in site.Features)188
 //    {
                            //    {189
 //        if (fea.Definition.SolutionId == FeatureID && fea.Definition.Status == SPObjectStatus.Online)
                            //        if (fea.Definition.SolutionId == FeatureID && fea.Definition.Status == SPObjectStatus.Online)190
 //        {
                            //        {191
 //            try
                            //            try192
 //            {
                            //            {193
 //                ti.Task.Execute(site.ID);
                            //                ti.Task.Execute(site.ID);194
 //            }
                            //            }195
 //            catch(Exception ee)
                            //            catch(Exception ee)196
 //            {
                            //            {197
 //                WriteEvent(site.Url, ee.ToString());
                            //                WriteEvent(site.Url, ee.ToString());198
 //                EventLogHandle.WriteException(ee);
                            //                EventLogHandle.WriteException(ee);199
 //            }
                            //            }200
 //        }
                            //        }201
 //    }
                            //    }202
 //}
                            //}203
 ti.Task.Execute(contentDbId);
                            ti.Task.Execute(contentDbId);204
 
                            205
 }
                        }206
 }
                    }207
 catch (Exception eee)
                    catch (Exception eee)208
 {
                    {209
 WriteEvent(ti.JobName, eee.ToString());
                        WriteEvent(ti.JobName, eee.ToString());210
 EventLogHandle.WriteException(eee);
                        EventLogHandle.WriteException(eee);211
 }
                    }212
 finally
                    finally213
 {
                    {214
 if (ti.CurrentTime == ti.JobTime)
                        if (ti.CurrentTime == ti.JobTime)215
 {
                        {216
 ti.CurrentTime = 0;
                            ti.CurrentTime = 0;217
 }
                        }218
 }
                    }219
 }
                }220
 }
            }221
 //// get a reference to the current site collection's content database
            //// get a reference to the current site collection's content database222
 //SPWebApplication webApplication = this.Parent as SPWebApplication;
            //SPWebApplication webApplication = this.Parent as SPWebApplication;223
 //SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
            //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
            //// get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database226
 //SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];
            //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
            //// create a new task, set the Title to the current day/time, and update the item229
 //SPListItem newTask = taskList.Items.Add();
            //SPListItem newTask = taskList.Items.Add();230
 //newTask["Title"] = DateTime.Now.ToString();
            //newTask["Title"] = DateTime.Now.ToString();231
 //newTask.Update();
            //newTask.Update();232
 //SPSecurity.RunWithElevatedPrivileges(delegate()
            //SPSecurity.RunWithElevatedPrivileges(delegate()233
 //{
            //{234
 //    try
            //    try235
 //    {
            //    {236
 //        using (StreamWriter sw = new StreamWriter("C:\\time.txt", false, System.Text.Encoding.UTF8))
            //        using (StreamWriter sw = new StreamWriter("C:\\time.txt", false, System.Text.Encoding.UTF8))237
 //        {
            //        {238
 //            sw.WriteLine("这是第{0}次写入,当前时间是:{1}", nCount.ToString(), DateTime.Now.ToLongDateString());
            //            sw.WriteLine("这是第{0}次写入,当前时间是:{1}", nCount.ToString(), DateTime.Now.ToLongDateString());239
 //        }
            //        }240
 //    }
            //    }241
 //    catch
            //    catch242
 //    {
            //    {243
 //    }
            //    }244
 //});
            //});245
 }
        }246
 static void WriteEvent(string SiteName, string msg)
        static void WriteEvent(string SiteName, string msg)247
 {
        {248
 SPSecurity.RunWithElevatedPrivileges(delegate()
           SPSecurity.RunWithElevatedPrivileges(delegate()249
 {
           {250
 try
               try251
 {
               {252
 using (StreamWriter sw = new StreamWriter("C:\\time.txt", true, System.Text.Encoding.UTF8))
                   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"));
                       sw.WriteLine("\n时间:{2}\n站点名称:{0}\n日志信息:{1}", SiteName, msg,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));255
 }
                   }256
 }
               }257
 catch
               catch258
 {
               {259
 }
               }260
 });
           });261
 }
        }262
 }
    }263

264
 class EventLogHandle
    class EventLogHandle265
 {
    {266
 static EventLog _eventLog = null;
        static EventLog _eventLog = null;267
 static EventLogHandle()
        static EventLogHandle()268
 {
        {269
 _eventLog = new EventLog("Application", ".", "SPTaskProvider");
            _eventLog = new EventLog("Application", ".", "SPTaskProvider");270
 }
        }271
 public static void WriteException(Exception e)
        public static void WriteException(Exception e)272
 {
        {273
 _eventLog.WriteEntry(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace), EventLogEntryType.Error);
            _eventLog.WriteEntry(string.Concat(e.Message, Environment.NewLine, Environment.NewLine, e.StackTrace), EventLogEntryType.Error);274
 }
        }275
 public static void WriteEvent(string [] strArray)
        public static void WriteEvent(string [] strArray)276
 {
        {277
 _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Information);
            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Information);            278
 }
        }279
 public static void WriteWarn(string[] strArray)
        public static void WriteWarn(string[] strArray)280
 {
        {281
 _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Warning);
            _eventLog.WriteEntry(string.Concat(strArray), EventLogEntryType.Warning);282
 }
        }283
 }
    }284
 }
}285

调试用控制台源
码:
 Code
Code Code
Code完成
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号