Windows服务中的线程中计时器 [英] Timer within Thread within Windows Service
问题描述
我无法弄清楚如何处理这个问题的最好办法。
I cant figure out how to proceed the best way with this problem.
现在我有一个窗口服务,唯一的任务是从数据库中收集数据具体的DSN,然后如果数据是有效的发送一封电子邮件。该服务包含蜱每5分钟再予并执行上述任务的定时器。
Right now I have a windows service which only task is to gather data from a database with a specific DSN and then send out an email if the data is valid. The service contains a timer which ticks every 5 minuts and performs the tasks above.
现在我需要重新编写Windows服务能够在1个多跑DSN。
我想使窗口服务中多个线程,然后再次让每个线程内seperat计时器。
这是一个好主意,怎么能这样做?我想避免为每个DSN Windows服务。
Now I need to re-write the windows service to be able to run on more than 1 DSN. I was thinking of making several threads inside the windows service and then again have a seperat timer inside each thread. Is this a good idea and how can this be done? I want to avoid having a windows service for each DSN.
生病尝试绘制它,如果我没有任何意义。
Ill try to draw it if I dont make any sense
Windows Service
线程1(DSN1)--- --------------------------线程2(DSN2)-------------------- --Thread3(DSN3)结果
定时器(蜱每隔X分钟再予)-----------------定时器(下同)--------- ----------------定时器(相同的)结果
逻辑()-------------------- - - - - - - - - - - - - -逻辑 - - - - - - - - - - - - ---------逻辑()
Thread1(DSN1)-----------------------------Thread2(DSN2)----------------------Thread3(DSN3)
Timer(ticks every X minuts)-----------------Timer(same)-------------------------Timer(same)
Logic()---------------------------------------------Logic---------------------------------Logic()
希望我的问题是有道理的:)
Hope my problem makes sense :)
推荐答案
据我所知每个定时器代表本身就是一个线程。 。认识到这一点,我会尝试动态地为每一个给定的DSN定时器对象
As far as I Know each timer represents a thread on its own. Knowing this, I would try to dynamically create timer objects for each given dsn.
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
private List<GetDataFromDSN> list = null;
protected override void OnStart(string[] args)
{
list = new List<GetDataFromDSN>();
// assume args contains your given dsn values
foreach (string dsn in args)
{
GetDataFromDSN newObj = new GetDataFromDSN();
newObj.DSN = dsn;
list.Add(newObj);
newObj.Start();
}
}
}
public class GetDataFromDSN
{
public string DSN { get; set; }
private Timer timer = null;
private double interval = 1000*60*5; // 5 minutes interval
public GetDataFromDSN()
{
// init your object
timer = new Timer(interval);
timer.Elapsed +=new ElapsedEventHandler(timer_Elapsed);
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
// do what ever you want
}
public void Start() // or even make timer public
{
timer.Start();
}
public void Stop()
{
timer.Stop();
}
}
这篇关于Windows服务中的线程中计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!