【问题标题】:Windows service scheduling to run daily once a day at 6:00 AMWindows 服务计划每天早上 6:00 运行一次
【发布时间】:2014-07-18 12:48:47
【问题描述】:

我创建了一个 Windows 服务,我希望该服务将安排在每天早上 6:00 运行。 下面是我写的代码:-

public Service1()
{
    InitializeComponent();
}

protected override void OnStart(string[] args)
{
    try
    {
        ExtractDataFromSharePoint();
    }
    catch (Exception ex)
    {
        //Displays and Logs Message
        _loggerDetails.LogMessage = ex.ToString();
        _writeLog.LogDetails(_loggerDetails.LogLevel_Error, _loggerDetails.LogMessage);
    }
}

在上面的代码中,您可以看到在OnStart 服务方法中,我正在调用函数ExtractDataFromSharePoint()。我将如何安排它在每天早上 6:00 运行。

【问题讨论】:

标签: c# windows-services


【解决方案1】:

在这里,您有 2 种方式来执行您的应用程序,以在每天早上 6 点运行。

1) 创建一个控制台应用程序并通过 Windows 调度程序在早上 6 点执行。

2) 在您的 Windows 服务中创建一个计时器 (System.Timers.Timer),该计时器在每个定义的时间间隔和您的函数中执行,您必须检查系统时间是否 = 早上 6 点然后执行您的代码

ServiceTimer = new System.Timers.Timer();
ServiceTimer.Enabled = true;
ServiceTimer.Interval = 60000 * Interval;
ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(your function);

注意:在您的函数中,您必须编写代码以在早上 6 点执行您的方法,而不是每次都

【讨论】:

  • 这可能不会在每天 6:00 执行,就好像我们设置的时间间隔可能不会让 Hrs 与 06 Hrs 重合。
  • 您好 Jinith,在这种情况下,您可以在函数中编写逻辑,例如 If( System.DateTime.Now() >= 6 AND LastExecutionDateTime.Date == Today.Date) { LastExecutionDateTime = System.日期时间.Now(); . }
  • 你觉得这样使用它怎么样? ServiceTimer.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds;
【解决方案2】:

您不需要为此提供服务。只需创建一个常规控制台应用程序,然后使用 Windows 调度程序在早上 6 点运行您的程序。服务是您需要程序一直运行的时候。

【讨论】:

    【解决方案3】:

    这是每天早上 6 点在服务中运行的代码。

    包括:

    using System.Threading;
    

    还要确保你在类中声明你的计时器:

    private System.Threading.Timer _timer = null;
    

    下面的 StartTimer 函数采用开始时间和间隔时间段,当前设置为早上 6 点开始,每 24 小时运行一次。如果需要,您可以轻松地将其更改为在不同的时间和间隔开始。

     protected override void OnStart(string[] args)
        {
            // Pass in the time you want to start and the interval
            StartTimer(new TimeSpan(6, 0, 0), new TimeSpan(24, 0, 0));
    
        }
        protected void StartTimer(TimeSpan scheduledRunTime, TimeSpan timeBetweenEachRun) {
            // Initialize timer
            double current = DateTime.Now.TimeOfDay.TotalMilliseconds;
            double scheduledTime = scheduledRunTime.TotalMilliseconds;
            double intervalPeriod = timeBetweenEachRun.TotalMilliseconds;
            // calculates the first execution of the method, either its today at the scheduled time or tomorrow (if scheduled time has already occurred today)
            double firstExecution = current > scheduledTime ? intervalPeriod - (current - scheduledTime) : scheduledTime - current;
    
            // create callback - this is the method that is called on every interval
            TimerCallback callback = new TimerCallback(RunXMLService);
    
            // create timer
            _timer = new Timer(callback, null, Convert.ToInt32(firstExecution), Convert.ToInt32(intervalPeriod));
    
        }
        public void RunXMLService(object state) {
            // Code that runs every interval period
        }
    

    【讨论】:

    • 请从 double firstExecution = current > scheduledTime 更正此问题? intervalPeriod + (current - scheduleTime) : scheduleTime - 当前;加倍 firstExecution = current > scheduledTime ? intervalPeriod - (current - scheduleTime) : scheduledTime - 当前;这将使正确的时间在下一个间隔运行
    • @cmartin 前面的评论把intervalPeriod + (current-scheduledTime) 改成intervalPeriod - (current-scheduledTime) 否则会延迟开始时间
    【解决方案4】:

    感谢@Rachit 的回答,现在我可以满足我的要求了。

    static  System.Timers.Timer _timer;
    static string _ScheduledRunningTime ="6:00 AM";
    public Service1()
    {
        InitializeComponent();
    }
    
    protected override void OnStart(string[] args)
    {
        try
        {
            _timer = new System.Timers.Timer();
            _timer.Interval = TimeSpan.FromMinutes(1).TotalMilliseconds;//Every one minute
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            _timer.Start();
        }
        catch (Exception ex)
        {
            //Displays and Logs Message
            _loggerDetails.LogMessage = ex.ToString();
            _writeLog.LogDetails(_loggerDetails.LogLevel_Error, _loggerDetails.LogMessage);
         }
     }
    
    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        //Displays and Logs Message
        _loggerDetails.LogMessage = "timer_Elapsed method at :"+DateTime.Now ;
        _writeLog.LogDetails(_loggerDetails.LogLevel_Info, _loggerDetails.LogMessage);
    
        string _CurrentTime=String.Format("{0:t}", DateTime.Now);
        if (_CurrentTime == _ScheduledRunningTime)
        {
            ExtractDataFromSharePoint();
        }
    }
    

    【讨论】:

      【解决方案5】:

      如果确实需要服务,请查看 Quartz.NET 为您做调度

      http://www.quartz-scheduler.net/

      【讨论】:

        【解决方案6】:

        这是调用 DB 并根据结果设置调度程序时间的代码:

        此外,您还可以调用一些 API 调用,这些调用本身会在此处发送常规 SMS/电子邮件。

        public void ScheduleService()
            {
                try
                {
                    dsData = new DataSet();
                    _timeSchedular = new Timer(new TimerCallback(SchedularCallBack));
                    dsData = objDataManipulation.GetInitialSMSConfig();
                    if (dsData.Tables[0].Rows.Count > 0)
                    {                    
                        DateTime scheduledTime = DateTime.MinValue;
                        scheduledTime = DateTime.Parse(dsData.Tables[0].Rows[0]["AUTOSMSTIME"].ToString());
                        if (string.Format("{0:dd/MM/YYYY HH:mm}", DateTime.Now) == string.Format("{0:dd/MM/YYYY HH:mm}", scheduledTime))
                        {
                            objDataManipulation.WriteToFile("Service Schedule Time Detected");
                            for (int iRow = 0; iRow < dsData.Tables[0].Rows.Count; iRow++)
                            {
                                    if (dsData.Tables.Count > 1)
                                    {
                                        if (dsData.Tables[1].Rows.Count > 0)
                                        {
                                            sendData(dsData);
                                        }
                                    }
                                    else
                                    {
                                        objDataManipulation.WriteToFile("No SMS Content Data !");
                                    }                        }
                        }
                        if (DateTime.Now > scheduledTime)
                        {
                            scheduledTime = scheduledTime.AddDays(1);
                        }                   
                        TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
                        string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
        
                        objDataManipulation.WriteToFile("TexRetail Service scheduled to run after: " + schedule + " {0}");
                        int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
                        //Change the Timer's Due Time.
                        _timeSchedular.Change(dueTime, Timeout.Infinite);                    
                    }
                }
                catch (Exception ex)
                {                              
                    objDataManipulation.WriteToFile("Service Error {0}" + ex.Message + ex.StackTrace + ex.Source);
                    using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(ServiceName))
                    {
                        serviceController.Stop();
                    }
                }
            }
        

        【讨论】:

          【解决方案7】:

          实际上我在这里从 app.config 文件获取时间间隔

             protected override void OnStart(string[] args)
              {            
                  Timer timer = new Timer();
                  this._dbServiceInterval = int.Parse(ConfigurationManager.AppSettings["ServiceInterval"].ToString());
                  timer.Interval = (double)this._dbServiceInterval;
                  timer.Enabled = true;
                  timer.Start();
                  timer.Elapsed += new ElapsedEventHandler(this.timerDispatcher_Elapsed);
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-07-12
            • 1970-01-01
            • 2015-05-19
            • 1970-01-01
            相关资源
            最近更新 更多