zoukankan      html  css  js  c++  java
  • 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("任务结束
    ");
                 btnOK.Enabled = true;
             });
         });
     }
    private void btnCancel_Click(object sender, EventArgs e)
    {
        ct.Cancel();
    }
    private void Do(CancellationTokenSource ct)
    {
        for (int i = 0; i < 3; i++)
        {
            if (!ct.IsCancellationRequested)
            {
                int restSeconds = GetMsgRestSeconds();
                if (restSeconds > 0)
                {
                    SetTextBoxText("请等待,暂停 " + restSeconds + " 秒
    ");
                    Thread.Sleep(restSeconds * 1000);
                }
                SetTextBoxText("正在发送第" + (i + 1).ToString() + "个客户...
    ");
                AppSettings.SetValue("LastMsgTime", DateTime.Now.ToString());
            }
            else
            {
               SetTextBoxText("任务" + (i + 1).ToString() + "取消
    ");             
            }
        }
    }
    /// <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个客户...
    任务结束

  • 相关阅读:
    《七哥说道》第十八章:何处不风雨,套路说江湖
    《七哥说道》第十七章:北漂青年,人海茫茫
    《闲扯Redis四》List数据类型底层编码转换
    《闲扯Redis三》Redis五种数据类型之List型
    《闲扯Redis二》String数据类型之底层解析
    《闲扯Redis一》五种数据类型之String型
    Js解析Json数据获取元素JsonPath与深度
    《七哥说道》第十六章:程序员,江湖见
    Swagger2.9.2进入API界面报NumberFormatException异常
    绝顶高手必经之路【资源共享】
  • 原文地址:https://www.cnblogs.com/gdjlc/p/3402933.html
Copyright © 2011-2022 走看看