What you want to do is to have a single method with flag
parameters that will be called every time one of the timers is elapsed. To achieve this without creating a lot of similar event handler methods you can use lambda statements:
void PrepareTimers() {
var timer1 = new Timer(TimerAction, 100, 5000, 0);
var timer2 = new Timer(TimerAction, 103, 5000, 0);
// etc
}
There I create a few timers with 5000 ms interval and make sure that TimerAction
is called with the parameter I want for this particular timer. The method itself could be along these lines:
void TimerAction(object flag) {
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Customers WHERE flag = @flag", _connection);
SqlParameter param = new SqlParameter();
param.ParameterName = "@flag";
param.Value = flag;
cmd.Parameters.Add(param);
// execute query
}
In my example I just use a parameterized select statement to read all the rows with correct flag. You'll probably want to do some update or delete logic, but the idea is the same - you want to do a parameterized SQL query and pass the parameter's value in method's argument.
Note that PrepareTimers
implementation that I gave is very simple and has to be rewritten using a loop if you need to use more than 2 timers:
List<int> _flagValues = new List<int> { 100, 103, 106, 107, 108, 109 };
void PrepareTimers(List<int> flagValues) {
foreach(int flagValue in flagValues) {
var timer = new Timer(TimerAction, flagValue, 5000, 0);
}
}
EDIT: I made a few edits to make sure I use System.Threading.Timer
insted of System.Timers.Timers
(see discussion). Sorry for the mess.