[英]Polling Service - C#
Will anobody be able to help me? 有人能帮助我吗?
I am creating a windows service that connects to a sql database and checks a date in the table and compares it to todays date and updates a field in that database for eg if the date is equal to todays date then the field will be set to true. 我正在创建一个连接到SQL数据库的Windows服务,并检查表中的日期并将其与今天的日期进行比较,并更新该数据库中的字段,例如,如果日期等于今天的日期,则该字段将设置为true 。
The problem I am having is that when i start the service it does not do that but when i do it in a normal form it works perfectly. 我遇到的问题是,当我启动服务时,它不会这样做但是当我以正常形式执行它时它完美地工作。
My code is below: 我的代码如下:
//System.Timers
Timer timer = new Timer();
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
int campid = 0;
var campRes = new ROS.Process.CampaignServiceController().GetCampainInfo();
foreach (var s in campRes)
{
campid = s.CampaignId;
if (s.CampEndDate.Date < DateTime.Today.Date)
{
//WriteDataToFile("Not Active : " + campid.ToString());
new ROS.Process.CampaignServiceController().SetCampainStatusFalse(campid);
}
else
{
//WriteDataToFile("Active : " + campid.ToString());
new ROS.Process.CampaignServiceController().SetCampainStatusTrue(campid);
}
}
}
Another way of doing this would be to wait on an event rather then using a timer. 另一种方法是等待事件而不是使用计时器。
ie 即
public class PollingService
{
private Thread _workerThread;
private AutoResetEvent _finished;
private const int _timeout = 60*1000;
public void StartPolling()
{
_workerThread = new Thread(Poll);
_finished = new AutoResetEvent(false);
_workerThread.Start();
}
private void Poll()
{
while (!_finished.WaitOne(_timeout))
{
//do the task
}
}
public void StopPolling()
{
_finished.Set();
_workerThread.Join();
}
}
In your Service 在您的服务中
public partial class Service1 : ServiceBase
{
private readonly PollingService _pollingService = new PollingService();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_pollingService.StartPolling();
}
protected override void OnStop()
{
_pollingService.StopPolling();
}
}
Set Timer.AutoReset = true. 设置Timer.AutoReset = true。 otherwise it will do its work only one time.
否则它只能完成一次工作。 but it's better to work with threading in windows services.
但最好在Windows服务中使用线程。
[edit] ah, yes. [编辑]啊,是的。 autoreset is true in default.
autoreset默认为true。 I put this too in my code: GC.KeepAlive( myTimer );
我把它放在我的代码中:GC.KeepAlive(myTimer); so the gc won't remove it if it is inactive.
所以如果它不活动,gc将不会删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.