簡體   English   中英

如何在.net中的任務計划程序中控制幾種方法

[英]How to control few methods in task scheduler in .net

我有一個如下所示的控制台應用程序,其中有4種方法,例如Sendmail(),Downloadfile(),ProcessFile(),ExportFIle() ,我將其作為任務調度程序運行,每天早上8:AM運行,但有時大約是12點時鍾,我只想運行ProcessFile()ExportFIle() 。所以我曾經做的是,我將在Visual Studio中打開應用程序,然后注釋Sendmail ()和Downloadfile (),這樣我只能運行其余兩個但是問題是如果我忘了取消注釋代碼,第二天早上8點,調度程序將僅運行兩個函數。有什么辦法可以在不注釋代碼的情況下管理這種情況?

namespace Testconsole
{
    class Program
    {
        static void Main(string[] args)
        {

            Sendmail();
            Downloadfile();
            ProcessFile();
            ExportFIle();
        }
    }
}

最簡單的解決方案是利用CronNet之類的調度框架

更新如果您不希望第三方dll來管理它-您可以在控制台應用程序中引入一些命令行參數:

  • 默認情況下,如果不傳遞任何參數-所有任務都將運行
  • 如果指定了特定的任務名稱-僅運行該任務
  • 介紹一些從字符串命令行參數到您的方法的簡單映射-簡單的Dictionary<string,Action>或只是一些反射-基於約定的映射

例如: myScheduler.exe ProcessFile ExportFile

您可以將每個任務安排為單獨的CronJob

您的代碼可能看起來像這樣(基於CronNet Wiki)

using System.Threading;
using CronNET;

namespace CronNETExample.Console
{
    class Program
    {
        private static readonly CronDaemon cron_daemon = new CronDaemon();            

        static void Main(string[] args)
        {
            cron_daemon.add_job(new CronJob("* * * * *", Sendmail));
            cron_daemon.add_job(new CronJob("* * * * *", Downloadfile));
            cron_daemon.add_job(new CronJob("* * * * *", ProcessFile));
            cron_daemon.add_job(new CronJob("* * * * *", ExportFIle));

            cron_daemon.start();

            // Wait and sleep forever. Let the cron daemon run.
            while(true) Thread.Sleep(6000);
        }
    }
}

您可以同時編譯兩個版本的代碼,而不必理會VS。

無論如何,一種更優雅的方式(無需進行任何注釋和編譯)將使用Quartz.Net之類的chron調度程序,並將您的程序用作Windows服務。

編寫配置XML文件。 然后,控制台應用程序必須讀取文件以決定要運行的方法,然后您可以在需要更改時更改XML,而不必更改代碼本身。

您還可以將應用程序拆分為4個不同的控制台應用程序,然后分別運行每個應用程序。 在自己預定的任務中。 通過使用Windows任務計划程序。

或者,您可以更改main方法以接受將指示要運行哪些方法的參數,然后將它們包括在已運行的計划任務中。

class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Sendmail();
            Downloadfile();
            ProcessFile();
            ExportFile();
        }

        foreach (string s in args)
        {
            switch (s)
            {
                case "SendMail":
                    Sendmail();
                    break;
                //etc.
            }
        }
    }
}

一種簡單的方法是將“執行器”功能包裝到兩個單獨的計划功能中:

namespace Testconsole
{
    class Program
    {
        static void Main(string[] args)
        {
          if (args[0] = "8")
            ScheduleFor8();
          if (args[0] = "12")
            ScheduleFor12();

        }
        static void ScheduleFor8() {
            Sendmail();
            Downloadfile();
            ProcessFile();
            ExportFIle();
        }
        static void ScheduleFor12() {
            ProcessFile();
            ExportFIle();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM