【问题标题】:How to Run a Windows Service at specific time each day如何在每天的特定时间运行 Windows 服务
【发布时间】:2014-03-28 19:15:36
【问题描述】:

我有一个 Windows 服务,我需要在一天中的特定时间运行。假设时间 id 是晚上 11:00。目前我有代码可以每天运行这个服务,但是如何在其中添加时间变量我不是能够得到。 这是我在 c# 中的代码..

protected override void OnStart(string[] args)
    {
        timer = new Timer();
        timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day 
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        start_timer();

    }

    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add your code here
        readDataFromAd();

    }
    private static void start_timer()
    {
        timer.Start();
    }

请帮助我定义时间以及间隔。时间应该是晚上 11:00,计时器应该每天执行方法。

【问题讨论】:

    标签: c# timer windows-services


    【解决方案1】:

    最好的选择是在 windows 服务中使用 Quartz schedular。使用石英,您还可以根据执行时间在单个服务中安排多个作业,例如每天早上 5 点。 ,每小时,每分钟,每周等。使用起来太灵活了。

    【讨论】:

    • 同意,另外还有windows scheduler
    【解决方案2】:

    Quartz 很棒,但如果您只想每天运行一次服务,那么内置的 Windows 任务计划程序也是一个不错的选择。

    你会:

    1. 更改您的服务以删除计时器/睡眠并从从 OnStart() 启动的线程中调用 readDataFromAd() (discussion on why a thread may be necessary here)
    2. 在任务计划程序中创建一个在晚上 11 点执行以下命令的任务:

      NET START 您的服务名称

    【讨论】:

      【解决方案3】:

      试试这个:

       protected override void OnStart(string[] args)
              {
      
                      _timer.Enabled = true;
      
                      DateTime currentTime = DateTime.Now;
                      int intervalToElapse = 0;
                      DateTime scheduleTime = Convert.ToDateTime(ConfigurationSettings.AppSettings["TimeToRun"]);
      
                      if (currentTime <= scheduleTime)
                          intervalToElapse = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
                      else
                          intervalToElapse = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
      
                      _timer = new System.Timers.Timer(intervalToElapse * 1000);
                      _timer.AutoReset = true;
                      _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
                      _timer.Start();
              }
      
      private void _timer_Elapsed(object sender, ElapsedEventArgs e)
              {
                 //do your thing
      //set it to run on a 24-hour basis
           _timer.Interval = 60 * 60 * 24 * 1000;
      
      }
      

      【讨论】:

        【解决方案4】:

        我建议您改变方法。服务通常用于始终运行的长时间运行的进程。对于按计划运行的进程,Windows 有一个名为“任务计划程序” 的内置组件,专为按计划运行应用程序而设计。

        您可以简单地将您的应用程序服务代码粘贴到 Windows 控制台应用程序中,然后使用 Windows Task Scheduler 安排生成的 exe 按照您认为合适的任何时间表运行。

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2011-11-06
          • 1970-01-01
          • 2011-01-23
          • 1970-01-01
          • 2013-12-21
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多