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 AutoJob
{
 public class AutoJobService : System.ServiceProcess.ServiceBase
 {
  /// <summary>
  /// 設計工具所需的變數。
  /// </summary>
  private System.ComponentModel.Container components = null;
  private System.Collections.ArrayList arrayList = null;
  private System.Threading.Timer timer = null;
   

  public AutoJobService()
  {
   // 此為 Windows.Forms 元件設計工具所需的呼叫。
   InitializeComponent();

   // TODO: 在 InitComponent 呼叫之後加入任何初始設定
  }

  // 處理序的主進入點
  static void Main()
  {
   System.ServiceProcess.ServiceBase[] ServicesToRun;
 
   // 在同一處理序中可以執行一個以上的使用者服務。
   // 若要將其他服務加入到這個處理序,請變更以下這行來建立第二個服務物件。例如
   //
   //   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
   //
   ServicesToRun = new System.ServiceProcess.ServiceBase[] { new AutoJobService() };

   System.ServiceProcess.ServiceBase.Run(ServicesToRun);
  }

  /// <summary>
  /// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改
  /// 這個方法的內容。
  /// </summary>
  private void InitializeComponent()
  {
   //
   // AutoJobService
   //
   this.AutoLog = false;
   this.ServiceName = "AutoJobService";
   
  }

  /// <summary>
  /// 清除任何使用中的資源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  /// <summary>
  /// 設定使服務能開始執行的事務。
  /// </summary>
  protected override void OnStart(string[] args)
  {
   // TODO: 在此加入啟動服務的程式碼。
   writeLog("AutoJobService Start !");

   arrayList = new ArrayList();
   string[] fileNames = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["appDir"], "*.dll");
   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
     {
      writeLog("An Exception was generated by " + fileName);
     }
    }
   }
  }
 
  /// <summary>
  /// 停止這項服務。
  /// </summary>
  protected override void OnStop()
  {
   // TODO: 在此加入停止服務所需執行的終止程式碼。
   foreach(object o in arrayList)
   {
    timer = (System.Threading.Timer) o;
    timer.Dispose();
    timer = null;
   }
   arrayList = null;
   writeLog("AutoJobService Stop !");
  }

  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.ConfigurationSettings.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();
   }
  }
 }
}

然後,編譯,在需要定時運行的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;
  }
 }
}

其中,Start表示啟動後做什麼事情;GETDUETIME表示,第一次執行的時間,可以返回一個固定的值,表示丟到WINDOWS SERVICE同級目錄下後多長時間執行,也可以寫一個固定的時間;GETPERIOD表示間隔多長時間執行一次。如果對時間有特殊的要求,可以在START裡面判斷,比如是不是星期一呀,或者是不是當月的第一天呀,等等。

以上代碼為公司的其它牛人開發,僅供用於學習目的,不得用於商業用途。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值