0

如何设置窗口服务的 onStart() 方法,以便在安装后第一次在上午 12 点执行,时间间隔工作正常,服务在提到的时间间隔后执行,但不在给定时间启动。

            public static System.Timers.Timer Timer;
            Double _timeinterval = 300 * 1000;// 6 mins
            protected override void OnStart(string[] args)
            {
            Timer = new System.Timers.Timer();

            Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            Timer.Interval = _timeinterval;
            Timer.Enabled = true;
            //method call to do operation
           }
            private void OnTimedEvent(object source, ElapsedEventArgs e)
              {
                //method call to do operation
              }
4

1 回答 1

1
  protected override void OnStart(string[] args)
    {

        aTimer = new System.Timers.Timer();

        string starttime = "01.25";
        //start time is 01.25 means 01:15 AM

        double mins = Convert.ToDouble(starttime);
        DateTime t = DateTime.Now.Date.AddHours(mins);
        TimeSpan ts = new TimeSpan();
        // ts = t - System.DateTime.Now;
        ts = t.AddDays(1) - System.DateTime.Now;
        if (ts.TotalMilliseconds < 0)
        {
            ts = t.AddDays(1) - System.DateTime.Now;
            // ts = t - System.DateTime.Now;
        }
        _timeinterval = ts.TotalMilliseconds;
       // _timeinterval now set to 1:15 am (time from now to 1:15AM)
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = _timeinterval;
        aTimer.Enabled = true;
       }
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
         {

           // operation to perform
           aTimer.Interval = 86400000; // now interval sets to 24 hrs

    }
于 2012-10-15T06:03:29.490 回答