(参考)VS 2005 C#實現的AutoJob【WINDOWS系統上按USER指定時間條件定時運行】(转)

C#實現的AutoJob【WINDOWS系統上按USER指定時間條件定時運行】    
首先建立一個類庫工程,名字叫:AutojobRun,代碼如下:

 using System;
using System.Threading;
using System.IO;

namespace AutoJob
{
 /// <summary>
 /// AutoJobRun 的摘要描述。
 /// </summary>
 public abstract class AutoJobRun
 {
  public AutoJobRun()
  {
   //
   // TODO: 在此加入建構函式的程式碼
   //
  }

  public abstract void Start(object obj);

  public abstract long GetDueTime();

  public abstract long GetPeriod();

  protected void writeLog(string detailDesc)
  {
   Monitor.Enter(this);
   string fullText = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + detailDesc;
   string fileFullName = System.Configuration.ConfigurationSettings.AppSettings["appDir"] + "\\Log\\" + this.GetType().Name + ".txt";
   checkFile(fileFullName);
   System.IO.StreamWriter sw = System.IO.File.AppendText(fileFullName);
   sw.WriteLine(fullText);
   sw.Flush();
   sw.Close();
   Monitor.Exit(this);
  }

  protected long timeTo(DateTime exeTime)
  {
   TimeSpan ts = exeTime.Subtract(DateTime.Now);
   long totalMilliseconds = ts.Days * 86400000 + ts.Hours * 3600000 + ts.Minutes * 60000 + ts.Seconds * 1000 + ts.Milliseconds;
   return totalMilliseconds;
  }

  private void checkFile(string fileName)
  {
   if(!System.IO.File.Exists(fileName))
   {
    System.IO.StreamWriter sw = System.IO.File.CreateText(fileName);
    sw.Close();
   }
  }
 }
}

然後,建立一個WINDOWS Service工程,叫AUTOJOB SERVICE,注意,此WINDOWS SERVICE要引用剛才上面編譯的AUTOJOBRUAN的DLL。具體代碼如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Reflection;
using System.IO;
using System.Threading;

namespace AutoJobService
{
    public partial class AutoJobService : ServiceBase
    {
        private System.Collections.ArrayList arrayList = null;
        private System.Threading.Timer timer = null;

        public AutoJobService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 設定使服務能開始執行的事務。
        /// </summary>
        protected override void OnStart(string[] args)
        {

            // TODO: 在此加入啟動服務的程式碼。
            if (!Directory.Exists(System.Configuration.ConfigurationManager.AppSettings["appDir"] + "\\Log"))
            {
                Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings["appDir"] + "\\Log");
            }
            writeLog("AutoJobService Start !");
            string[] fileNames = Directory.GetFiles(System.Configuration.ConfigurationManager.AppSettings["appDir"], "*.dll");
            //string[] fileNames = Directory.GetFiles(System.Windows.Forms.Application.StartupPath, "*.dll");
            if (fileNames.Length <= 0)
            {
                writeLog("Null DLL !");
            }
            arrayList = new ArrayList();
            foreach (string fileName in fileNames)
            {
                Assembly a = Assembly.LoadFrom(fileName);
                Type[] types = a.GetTypes();
                foreach (Type t in types)
                {
                    try
                    {
                        if (t.IsSubclassOf(typeof(AutoJob.AutoJobRun)))
                        {
                            object o = Activator.CreateInstance(t);
                            AutoJob.AutoJobRun ajr = (AutoJob.AutoJobRun)o;

                            long period = ajr.GetPeriod();
                            long dueTime = ajr.GetDueTime();

                            TimerCallback tcb = new TimerCallback(ajr.Start);
                            timer = new System.Threading.Timer(tcb, null, dueTime, period);

                            arrayList.Add(timer);
                        }
                    }
                    catch (Exception ex)
                    {
                        writeLog("An Exception was generated by " + fileName + "。" + ex.Message);
                    }
                }
            }
        }

        /// <summary>
        /// 停止這項服務。
        /// </summary>
        protected override void OnStop()
        {
            // TODO: 在此加入停止服務所需執行的終止程式碼。
            if (arrayList != null)
            {
                foreach (object o in arrayList)
                {
                    timer = (System.Threading.Timer)o;
                    timer.Dispose();
                    timer = null;
                }
                arrayList = null;
                writeLog("AutoJobService Stop !");
            }
            else
            {
                writeLog("AutoJobService Stop !null");
            }
        }

        private void writeLog(string detailDesc)
        {
            Monitor.Enter(this);
            string fullText = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + detailDesc;
            string fileFullName = System.Configuration.ConfigurationManager.AppSettings["appDir"] + "\\Log\\AutoJobService.txt";
            checkFile(fileFullName);
            System.IO.StreamWriter sw = System.IO.File.AppendText(fileFullName);
            sw.WriteLine(fullText);
            sw.Flush();
            sw.Close();
            Monitor.Exit(this);
        }

        private void checkFile(string fileName)
        {
            if (!System.IO.File.Exists(fileName))
            {
                System.IO.StreamWriter sw = System.IO.File.CreateText(fileName);
                sw.Close();
            }
        }
    }
}



namespace AutoJobService
{
    partial class AutoJobService
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.AutoLog = false;
            this.ServiceName = "AutoJobService";

        }

        #endregion
    }
}
注意:VS 2005 的 读取Config 文件的内容 要引用System.Configuration 2.0.0, 建立一个App.Config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
  <add key="appDir" value="E:\\AutoJobService"></add>
 </appSettings>
</configuration>

添加安装组件:

  在设计页面上点右键,出现菜单后,选择添加安装程序。这时会出现一个新的页面,页面上有个控件 serviceProcessInstaller1和serviceInstaller1

  在 serviceProcessInstaller1中把属性Account改为LocalSystem

  在把serviceInstaller1中把属性Parent 改为serviceProcessInstaller1 ServiceName属性是管生成服务后的名子

  添加完成之后,生成一下(假设名为W2.exe)。到相应的文件夹找到生成的exe文件,找到时会发现有两个.exe用名子比较短的那个。把这个文件拷到一个好记的文件夹中如F盘根目录。

  这时就是要把个服务安装一下。进入cmd中的画面,进入Framework2.0的文件如:

  cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

  后在打

  InstallUtil f:\w2.exe     卸载服务是 InstallUtil f:\w2.exe -u
然後,編譯,在需要定時運行的SERVER上,安裝此服務,然後,將需要定時運行的代碼也寫成DLL【類庫工程,此類庫工程也需要引用剛才上面提到的哪個AUTUJOBRUN的DLL】,放在此WINDOWS DLL的同一個目錄下。然後,此WINDOWS 服務回按要求調用此DLL,來完成USER的需求。

完成任務的DLL的SAMPLE如下,注意,一定要引用AUTOJOBRUN的哪個DLL。

using System;

namespace AutoTask
{
 /// <summary>
 /// Class1 的摘要描述。
 /// </summary>
 public class AutoTaskA : AutoJob.AutoJobRun
 {
  public AutoTaskA()
  {
   //
   // TODO: 在此加入建構函式的程式碼
   //
  }

  public override void Start(object o)
  {
   this.writeLog(this.GetType().FullName + " Job Start");
  }

  public override long GetDueTime()
  {
   return 10000;
  }

  public override long GetPeriod()
  {
   return 30000;
  }
 }
}

posted on 2008-03-20 15:33  KenL  阅读(226)  评论(0)    收藏  举报

导航