-2
partial class TestService : ServiceBase
{
FileStream fs;
StreamWriter sw;
public TestService()
{
InitializeComponent();
fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create);
sw = new StreamWriter(fs);
}
protected override void OnStart(string[] args)
{
try
{
if (!File.Exists(@"C:\SampleLast.txt"))
{
fs = new FileStream(@"C:\SampleLast.txt", FileMode.Create);
sw = new StreamWriter(fs);
}
sw.WriteLine("Service start {0}", DateTime.Now.ToString());
Timer timerNew = new Timer();
timerNew.Elapsed += new ElapsedEventHandler(timerNew_Elapsed);
timerNew.Enabled = true;
timerNew.Interval = 4000;
timerNew.Start();
sw.WriteLine(timerNew.Enabled.ToString());
sw.Flush();
}
catch(Exception Ex)
{
sw.WriteLine(Ex.ToString());
sw.Flush();
}
}
void timerNew_Elapsed(object sender, ElapsedEventArgs e)
{
sw.WriteLine("timer is working...{0}", DateTime.Now.ToString());
SqlConnection conn;
SqlCommand comm;
conn = new SqlConnection(@"Data Source=.;Initial Catalog=MailDB;Integrated Security=True");
comm = new SqlCommand("select Text,product from Source", conn);
conn.open();
SqlDataReader rd = comm.ExecuteReader();
while (rd.Read())
{
if (Convert.ToInt32(rd["Text"]) < 20)
{
sw.WriteLine("{0} stock state {1}", rd["product"].ToString(), rd["stock"].ToString());
}
}
sw.Flush();
}
protected override void OnStop()
{
}
}
我想爲我的項目使用Windows服務。當我使用這些代碼時,我沒有任何問題。使用sql的Windows服務
問題是我在定時器模塊中添加了一些SQL代碼。我在SampleLast.text文件中有一些效果。只需運行代碼OnStart()
方法。我不明白什麼是問題。問題是當我使用sqllconnection和sqlcommand代碼,定時器dosent工作。
你需要**至少告訴我們*您遇到什麼問題(錯誤信息等)***樣的... –
如果您可以根據評論中的建議改善您的問題,請將其標記爲供審查主持人關注。 –
另請參見:**您正在使用哪個** Timer(無法從您的代碼中說出 - 您沒有顯示「使用......」語句)? .NET框架中至少有三種不同的Timer類,並不是所有的類都可以很好地工作。 NT服務.... –