I want to make a timer running in the server that runs a method() every 60 seconds
now i have done -sort of- that using the code below
public class Alarm
{
public Alarm(AppDbContext _db)
{
db = _db;
}
private static Timer aTimer;
private AppDbContext db;
public void StartTimerEvent()
{
// Create a timer and set a 60 second interval.
aTimer = new Timer();
aTimer.Interval = 60000;
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += (source, e) => CheckDBEvents(source, e);
// Have the timer fire repeated events (true is the default)
aTimer.AutoReset = true;
// Start the timer
aTimer.Enabled = true;
}
private void CheckDBEvents(Object source, ElapsedEventArgs e)
{
//get data from db with matching queries
List<Grocery> DataList = db.Grocery.Where(G => G.basic).Select(G => new Grocery
{
Id = G.Id,
Timeout = G.Timeout
}).ToList();
}
}
the method() is CheckDBEvents() and what it does is it accesses the dbcontext instance and looks for some data to save to to a local constant variable Called DataList
problem : every time i try passing the context (Dbcontext) instance --in the controller or any other class-- to the CheckDBEvents() method, the context is disposed -DbContext Disposed Exception. the caller
var t = new Alarm(db);
t.StartTimerEvent();
My tires :-
- making alarm a static class :
Now if i can do that It would be amazing ... but can not operate on DbContext since you can't call instance on DbContext in a static class you have to pass it from who ever calls it, which leads to the same problem :db is Disposed and don't get passed
public static void StartTimerEvent(AppDbContext db)
{
.....
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += (source, e) => CheckDBEvents(source, e, db
//DbContext is Disposed here and
//don't get passed'
);
also constant classes and Dbcontext don't get along very well from what i have read.
Long Story Short -I want to keep instance of dbContext in another class rather than controllers. without it being disposed.
if anyone have and idea what how to do this or have a source code to server side timer or anything like that please comment, I have been stuck for 2 days