Using timers to query DB table rows with different flag column values
I want to identify specific mysql db column value using timer.
For example, I have 6 timers and in database I have a column namedflag
, and its values are 100, 100, 100, 103, 103, 106, 107, 107, 107, 108, 108, 109
. I want:
1st timer to work with three 100 values,开发者_如何学运维
2nd timer to work with two 103,
3rd timer to work with one 106 value,
4th timer to work with three 107 values,
5th timer to work with two 108 values and
6th timer to work with one 109 values.
How do I assign these values (100, 103, 106
) to my timers?
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.
You have to do a parametric query: every time that timer expire, you can di a different query base on timer's value. The WHERE condition is the way
精彩评论