日期:2014-05-18  浏览次数:20787 次

VS2005写windows 服,TIMER没工作,求助!
我按照网上的例子,建了windows 服务工程,加了个TIMER(组件面板的),TIMER.InterVAL=200 TIMER.Enable=true.写了一下代码,没秒写5条记录入数据库。
 private void timer1_Tick(object sender, EventArgs e) 
  {
  SqlConnection conn = new SqlConnection("Data Source=172.16.8.1;Initial Catalog=scei;Persist Security Info=True;User ID=sa;Password=elara");
  SqlCommand comm = new SqlCommand(" INSERT INTO [tempTable] ([NAME]) VALUES ('测试的数据') ", conn);
  conn.Open();
  comm.ExecuteNonQuery();
  conn.Close();
  }
服务正常安装启动了,但是TIMER没工作,数据没写人。
数据库访问代码无误,放在
 protected override void OnStart(string[] args)
  {
  // TODO: 在此处添加代码以启动服务。
  }
执行是对的。
求助各位高手!

------解决方案--------------------
你是不是错用了System.Windows.Forms.Timer 啊?这个Timer无法在服务里面执行的,你应该用System.Timers.Timer。

System.Windows.Forms.Timer class
Provides reference information on the class, used for Windows Forms timers, and its members.

System.Timers.Timer class
Provides reference information on the System.Timers..::Timer class that is used by server-based timers.

------解决方案--------------------
Timers.Timer没有Tick这个方法的。
------解决方案--------------------
using System;
using System.Timers;

public class Timer1
{
private static System.Timers.Timer aTimer;

public static void Main()
{
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler 
// from allowing aggressive garbage collection to occur 
// before the method ends. (See end of method.)
//System.Timers.Timer aTimer;

// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();

// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
}

// Specify what you want to happen when the Elapsed event is 
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */



------解决方案--------------------
你可以用起线程的方式替代timer
------解决方案--------------------
用System.Threading.Timer