本人想写个windows服务,根据XML数据读参数,并设置相应的时间间隔。。但timer运行一下就中断了。。想请大家帮忙分析解决。。。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Xml;
using System.Threading;
using System.Web;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Data.SqlClient;
namespace WServiceMk_html
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
System.Threading.Thread.Sleep(10000);
string filepath = System.Windows.Forms.Application.StartupPath + "\\XmlData.xml";
DataSet ds = new DataSet();
ds.ReadXml(filepath);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//arylst.Clear();
System.Threading.Timer tm;
int WebTime = Convert.ToInt32(ds.Tables[0].Rows[i]["WebTime"].ToString());
ArrayList arylst = new ArrayList();
arylst.Add(ds.Tables[0].Rows[i]["WebName"].ToString());
arylst.Add(ds.Tables[0].Rows[i]["WebUrl"].ToString());
tm = new System.Threading.Timer(new TimerCallback(TimerTest), arylst, 0, WebTime * 6);
//System.Configuration.ConfigurationSettings.AppSettings
}
}
protected override void OnStart(string[] args)
{
}
private void TimerTest(object obj)
{
ArrayList list = (ArrayList)obj;
SqlConnection con = new SqlConnection("server=.;uid =sa;pwd=111111;database=mydatabase");
con.Open();
string sql;
sql = "insert into TestTimer values('" + list[0].ToString() + "','" + list[1].ToString() + "')";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
}
protected override void OnStop()
{
}
}
}
xml数据
Code
xml数据中的webtime就是每隔多长时间就运行一次。。。,并把它对应的webname,和webUrl做参数传给方法里面。。。
System.Threading.Timer tm;
不能设置成局部变量,应该放在类中作为成员变量,因为局部变量的生命周期就在方法内有效,而你的方法就是一个构造函数,一次执行就完事了!改一下试试