日期:2014-05-17  浏览次数:21080 次

C#定时执行一个操作
一个客户端向服务器端socket发送报文,但是服务器端限制了发送频率,假如10秒内只能发送1次,这时客户端也要相应的做限制,初步的想法是在配置文件中保存上次最后发送的时间,当前发送时和这个上次最后时间做比较,根据情况马上发送还是休眠相应的时间。
举个例子,服务器发送频率限制是10秒,上次最后发送时间是10:00:00,有两种情况:
(1)当前时间是10:00:03,则过7秒后发送;
(2)当前时间是10:02:00,则马上发送。

App.config
<!--发送频率限制(秒)-->
<add key="MsgTimeLimit" value="10"/>
<!--上次最后发送时间-->
<add key="LastMsgTime" value="2013-11-1"/>
Test.cs
CancellationTokenSource ct;
private void btnOK_Click(object sender, EventArgs e)
{
     btnOK.Enabled = false;

     Task t = new Task(() => Do(ct));
     ct = new CancellationTokenSource();
     t.Start();
     t.ContinueWith((x) =>
     {
         this.SafeCall(() =>
         {
             richTextBox1.AppendText("任务结束\r\n");
             btnOK.Enabled = true;
         });
     });
 }
private void btnCancel_Click(object sender, EventArgs e)
{
    ct.Cancel();
}
/// <summary>
/// 获取发送剩余的时间
/// </summary>
/// <returns></returns>
private int GetMsgRestSeconds()
{
    int msgTimeLimit = 0;
    //获取要限制的间隔时间(秒)
    int.TryParse(AppSettings.GetValue("MsgTimeLimit"), out msgTimeLimit);
    if (msgTimeLimit == 0)
        return 0;
    //最近一次时间
    string lastMsgTime = AppSettings.GetValue("LastMsgTime");
    DateTime dtLastMsgTime = DateTime.MinValue;
    DateTime.TryParse(lastMsgTime, out dtLastMsgTime);
    DateTime dtNow = DateTime.Now;      
    if (dtLastMsgTime == DateTime.MinValue || dtLastMsgTime >= dtNow)
        return 0;                 
    TimeSpan ts = dtNow - dtLastMsgTime;
    int restSeconds = 0;
    if (msgTimeLimit > ts.TotalSeconds)
    {
        restSeconds = msgTimeLimit - (int)ts.TotalSeconds;
        restSeconds = restSeconds < 0 ? 0 : restSeconds;
    }
    return restSeconds;
}

其中
AppSettings.SetValue()和AppSettings.GetValue()方法见:
http://blog.csdn.net/gdjlc/article/details/8284799

SafeCall是个扩展方法
public static void SafeCall(this Control ctrl, Action callback)
{
    if (ctrl.InvokeRequired)
        ctrl.Invoke(callback);
    else
        callback();
}


点击【确认】按钮执行结果如下:

正在发送第1个客户...
请等待,暂停 10 秒
正在发送第2个客户...
请等待,暂停 10 秒
正在发送第3个客户...
任务结束

过了3秒钟,点击【确认】按钮并在执行完第一个操作按【取消】执行结果如下:

请等待,暂停 7 秒
正在发送第1个客户...
请等待,暂停 10 秒
正在发送第2个客户...
任务3取消
任务结束

过了5秒钟,点击【确认】按钮执行结果如下:

请等待,暂停 5 秒
正在发送第1个客户...
请等待,暂停 10 秒
正在发送第2个客户...
请等待,暂停 10 秒
正在发送第3个客户...
任务结束