码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET 自动更新数据

时间:2015-07-17 16:00:29      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

最近工作的时候需要完成一个自动发送数据给WEBSERVICE,以前没有弄过,经过网上的搜索终于完成了任务。

以下就是我完成的方法:

1.首先创建接口

技术分享
/// <summary>
/// 定时发送接口方法
/// </summary>
public interface ISendMessage
{
    void SendMessage();
}
View Code

2.新建类,继承接口创建方法,控制执行方法条件

技术分享
/// <summary>
/// 定时发送
/// </summary>
public class SMJob : ISendMessage
{
    /// <summary>
    /// 发送数据方法
    /// </summary>
    public void SendMessage()
    {
            string now = DateTime.Now.ToString("HH:mm");
            if (now == sciModel.SendTime)
            {//添加操作方法
         }
            else
                Thread.Sleep(5000);
    }
}            
View Code

 

3.新建类,在类中新建必要字段

技术分享
public class SendConfiguration
{
    /// <summary>
    /// 时间间隔
    /// </summary>
    private int sleepInterval;

    /// <summary>
    /// 任务列表
    /// </summary>
    private ArrayList jobs = new ArrayList();


    public int SleepInterval { get { return sleepInterval; } }

    public ArrayList Jos { get { return jobs; } }

    /// <summary>
    /// 构造函数
    /// </summary>
    public SendConfiguration(int newSleepInterval)
    {
        this.sleepInterval = newSleepInterval;
    }
}
View Code

4.新建线程工作类,添加开启线程方法

技术分享
public class SendJob
{
    private SendConfiguration sendConfig = null;

    public SendJob(SendConfiguration sc)
    {
        sendConfig = sc;
    }

    /// <summary>
    /// 开启方法
    /// </summary>
    public void Start()
    {
        while (true)
        {
            foreach (ISendMessage job in sendConfig.Jos)
            {
                ThreadStart ts = new ThreadStart(job.SendMessage);
                Thread thread = new Thread(ts);
                thread.Start();
                Thread.Sleep(sendConfig.SleepInterval);
            }
        }
    }

}
View Code

此刻上面的操作完成以后,我们就需要在Global.asax文件中进行代码的添加

5.在Application_Start方法中添加线程启动

技术分享
//开启线程
SendConfiguration config = new SendConfiguration(50000);
config.Jos.Add(new SMJob());
SendJob sendJob = new SendJob(config);
System.Threading.ThreadStart ts = new System.Threading.ThreadStart(sendJob.Start);
System.Threading.Thread newTheard = new System.Threading.Thread(ts);
newTheard.Start();
View Code

以上就已经完成了功能,如果需要在关闭任务后,关闭线程那么要添加一下方法

技术分享
    void Application_End(object sender, EventArgs e) 
    {
        //  在应用程序关闭时运行的代码
       if (newTheard != null)
               newTheard.Abort();
    }
View Code

如果大家有什么指教,希望大家提出来,我能多学学东西

 

ASP.NET 自动更新数据

标签:

原文地址:http://www.cnblogs.com/suiyuelianyun/p/4654640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!