1

Ive got a service which currently i believe is running every 10 min, but i want it to run at 7pm every day, what do i need to change? ....

 private Timer _timer;
    private DateTime _lastRun = DateTime.Now;

    protected override void OnStart(string[] args)
    {
        _timer = new Timer(10 * 60 * 1000); // every 10 minutes??
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {

        if (_lastRun.Date < DateTime.Now.Date)
        {
            // stop the timer 
            _timer.Stop();               

            try
            {
                SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
                test.Import();
            }
            catch (Exception ex) { }

            _lastRun = DateTime.Now;
            _timer.Start();
        }
    }
Beginner
  • 28,539
  • 63
  • 155
  • 235
  • 4
    Why are you using a service for this at all? Set it up as a scheduled task. – M.Babcock Apr 17 '12 at 15:59
  • 2
    So you took the accepted answer in http://stackoverflow.com/questions/503564/how-might-i-schedule-a-c-sharp-windows-service-to-perform-a-task-daily and pasted it into a new question instead of looking at the answer with the most upvotes right below it. – Till Apr 17 '12 at 16:05

2 Answers2

1

Windows Service is a continuosly running task. If you are looking for something which needs to run at a Specified time, Write a Scheduled Task, Other good link.

Community
  • 1
  • 1
Sandeep
  • 7,156
  • 12
  • 45
  • 57
1

Replacing:

if (_lastRun.Date < DateTime.Now.Date)
{
}

with:

DateTime startAt = DateTime.Today.AddHours(19);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
}

will probably do the trick. But I would prefer to use a scheduled task as has been suggested already

musefan
  • 47,875
  • 21
  • 135
  • 185
  • this does it ever 7 hours doest it? not at 7pm every evening? – Beginner Apr 17 '12 at 16:10
  • @Beginner: Actually it did it a 7am everyday, I have changed it now though. Note that `DateTime.Today` gets current date at 0 hours, then we add 19 hours to make it 7pm for comparing. We check two things after that.. first, if it hasn't run since the schedule time. And then, we make sure the scheduled time is in the past – musefan Apr 17 '12 at 16:20