Reputation: 664
I was wondering if it is possible if it is possible to create background tasks, what I mean is, in asp.net every user has his own instance so if I was to create a timer, when 2 users are on it will create 2 instances of a timer which I don't want.
I basically want a timer that is one instance and is independent. The reason I want to do this is because I want to do a SQL query every 5 minutes or so, and I don't want 2 users running it at the same time because then it wouldn't be 5 minutes apart it could be 2 mins and 30 secs apart.
USER1 --- ASP.NET INSTANCE USER2 --- ASP.NET INSTANCE
TIMER --- NOTHING TO DO WITH USERS
I have hear of things like web services and Quartz.net but I am unsure that it is what I want.
Hopefully it makes sense :)
Upvotes: 1
Views: 39
Reputation: 3321
Actually, Quartz.NET is the best solution because it's made for it: running tasks on a scheduled basis. If, for some reasons, you don't want to use it, the simplest way is to use a Timer object inside a singleton class; you can start the timer in your global.asax and this will provide you with a single timer that will be shared between all your users. Something like:
public class SingletonTimer
{
private static SingletonTimer _instance = null;
private Timer _myTimer;
protected SingletonTimer()
{
_myTimer = new Timer(Callback, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
}
private void Callback(object state)
{
// SQL QUERY
}
public static SingletonTimer GetInstance()
{
return _instance ?? (_instance = new SingletonTimer());
}
}
This is however a not stable solution because after 20 minutes of inactivity IIS will kill your pool and and the timer will stop running; the best thing to do is to host a Quart.NET scheduler in a different process, like a windows service.
Upvotes: 2