how to have a function run inside a service every 10 minutes?

后端 未结 5 987
时光取名叫无心
时光取名叫无心 2021-02-01 11:16

I have a windows service running, inside this i want to run a function every then minutes. I have found some code but it doesn\'t seem to work? I have a logger and it does not s

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 11:33

    Try starting the timer,

    protected override void OnStart(string[] args)
        {
           // SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
           // test.Import();
             log.Info("Info - Service Started");
            _timer = new Timer(10 * 60 * 1000); // every 10 minutes??
                _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start();
        }
    
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            log.Info("Info - Check time");
            DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48);
            if (_lastRun < startAt && DateTime.Now >= startAt)
            {
                // stop the timer 
                _timer.Stop();               
    
                try
                {
                    log.Info("Info - Import");
                    SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
                    test.Import();
                }
                catch (Exception ex) {
                    log.Error("This is my error - ", ex);
                }
    
                _lastRun = DateTime.Now;
                _timer.Start();
            }
        }
    

提交回复
热议问题