Using timers to query DB table rows with different flag column values

孤者浪人 提交于 2019-12-14 03:34:47

问题


I want to identify specific mysql db column value using timer.
For example, I have 6 timers and in database I have a column named flag, 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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/7460014/using-timers-to-query-db-table-rows-with-different-flag-column-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!