2

I have a windows service running. Within it the task runs currently at 7pm every day. What is the best way to have it run say fir example at 9.45am, 11.45am, 2pm, 3.45pm, 5pm and 5.45pm.

I know i can have scheduled task to run the function but i would like to know how to do this within my windows service. Current code below:

private Timer _timer;
private DateTime _lastRun = DateTime.Now;
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

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(19);
    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();
   }
}
Beginner
  • 28,539
  • 63
  • 155
  • 235

4 Answers4

5

Consider using Quartz.net and CronTrigger.

empi
  • 15,755
  • 8
  • 62
  • 78
  • I have downloaded Quartz could you possibly show me an example of how i would implement CronTrigger in my code? – Beginner Apr 30 '12 at 08:37
  • Check the tutorial http://quartznet.sourceforge.net/tutorial/index.html and ask if you have any specific questions – empi Apr 30 '12 at 08:39
5

In case you dont want to go for cron or quartz, write a function to find time interval between now and next run and reset the timer accordingly, call this function on service start and timeelapsed event. You may do something like this (code is not tested)

   System.Timers.Timer _timer;
    List<TimeSpan> timeToRun = new List<TimeSpan>();
    public void OnStart(string[] args)
    {

        string timeToRunStr = "20:45;20:46;20:47;20:48;20:49";
        var timeStrArray = timeToRunStr.Split(';');
        CultureInfo provider = CultureInfo.InvariantCulture;

        foreach (var strTime in timeStrArray)
        {
            timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
        }
        _timer = new System.Timers.Timer(60*100*1000);
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        ResetTimer();
    }


    void ResetTimer()
    {
        TimeSpan currentTime = DateTime.Now.TimeOfDay;
        TimeSpan? nextRunTime = null;
        foreach (TimeSpan runTime in timeToRun)
        {

            if (currentTime < runTime)
            {
                nextRunTime = runTime;
                break;
            }
        }
        if (!nextRunTime.HasValue)
        {
            nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
        }
        _timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
        _timer.Enabled = true;

    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        _timer.Enabled = false;
        Console.WriteLine("Hello at " + DateTime.Now.ToString());
        ResetTimer();
    }
Brijesh Mishra
  • 2,738
  • 1
  • 21
  • 36
0

If u are clear abt what schedule it should run..then change time interval for timer in the timeelapsed event so that it runs according to schedule..i've never tried though

Im Hari
  • 68
  • 2
  • 10
0

I would use a background thread and make it execute an infinite loop which does your work and sleeps for 15 minutes. It would be a lot cleaner and more simple for service code than using a timer.

See this article on MSDN.

Marek Dzikiewicz
  • 2,844
  • 1
  • 22
  • 24