• 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
     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


    Code

    完成
  • 相关阅读:
    [WPF] 修改进度条样式实现斑马进度条
    [WPF] 继承Shape实现弧形、扇形控件
    ILRuntime 热更官网
    (转)Unity资源打包学习笔记(一)、详解AssetBundle的流程
    (转)基于python脚本,实现Unity全平台的自动打包
    (转)Unity实现c#热更新方案探究(三)
    (转)Unity实现c#热更新方案探究(二)
    (转)Unity实现c#热更新方案探究(一)
    (转)Unity C#热更新方案 ILRuntime学习笔记(一) Hello World
    中国已进入“零工经济”时代
  • 原文地址:https://www.cnblogs.com/LifelongLearning/p/1212778.html
Copyright © 2020-2023  润新知