anthonypliu
anthonypliu

Reputation: 12437

Creating a windows service that runs an endless loop

I only do web development using MVC4 so I haven't really worked with Windows services. I am trying to create a service that will query my database every 5 seconds and check for specific results. If results come up then run my custom code. I originally tried doing this in my Global.asax file using the Timer class which I found it is a bad practice:

var timer = new Timer(5000);
timer.Elapsed += new ElapsedEventHandler(Callback);
timer.Interval = 5000;
timer.Enabled = true;

I was told that a Windows service would be best for this problem. Are there any tutorials or code snippets out there?

UPDATE:

Sorry I realize that was vague.

Im just looking for the best possible way to check my database to see if any of my records have hit their "end time" (imagine creating an auction and setting an end time for it, so when the auction ends i can send an email out notifying the user). I tried this using the Timer in my global.asax but i know there are plenty of problems with that, so i was suggested by another user to create a windows service, is that correct? if so where can i look to get started on that

Upvotes: 0

Views: 3102

Answers (1)

Heinrich
Heinrich

Reputation: 2214

I'm not to sure at the complexity that you are going for, but here is a simple template that you could play around with and see what happens:

using System;
using System.ServiceModel;
using System.ServiceProcess;


namespace MyService
{
   public class MyWindowsService:ServiceBase
   {
    public ServiceHost serviceHost = null;

    private static System.Timers.Timer scheduledTimer;

    public MyWindowsService()
    {
        ServiceName = "MyService";
        //Additional Initilizing code.
    }

    public static void Main()
    {
        ServiceBase.Run(new MyWindowsService());
    }

    protected override void OnStart(string[] args)
    {
        scheduledTimer = new System.Timers.Timer();
        scheduledTimer.AutoReset = true;
        scheduledTimer.Enabled = true;
        scheduledTimer.Interval = 5000;
        scheduledTimer.Elapsed += new System.Timers.ElapsedEventHandler(scheduledTimer_Elapsed);
        scheduledTimer.Start();
    }

    void scheduledTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //DO CHECK.
    }

    protected override void OnStop()
    {
        if (scheduledTimer != null)
        {
            scheduledTimer.Stop();
            scheduledTimer.Elapsed -= scheduledTimer_Elapsed;
            scheduledTimer.Dispose();
            scheduledTimer = null;
        }
    }

    private void InitializeComponent()
    {
        this.ServiceName = "MyService";
    }
}

Upvotes: 1

Related Questions