标签:
最近工作的时候需要完成一个自动发送数据给WEBSERVICE,以前没有弄过,经过网上的搜索终于完成了任务。
以下就是我完成的方法:
1.首先创建接口
/// <summary> /// 定时发送接口方法 /// </summary> public interface ISendMessage { void SendMessage(); }
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); } }
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; } }
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); } } } }
此刻上面的操作完成以后,我们就需要在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();
以上就已经完成了功能,如果需要在关闭任务后,关闭线程那么要添加一下方法
void Application_End(object sender, EventArgs e) { // 在应用程序关闭时运行的代码 if (newTheard != null) newTheard.Abort(); }
如果大家有什么指教,希望大家提出来,我能多学学东西
标签:
原文地址:http://www.cnblogs.com/suiyuelianyun/p/4654640.html