gre*_*ame 3 c# service polling
有人能帮助我吗?
我正在创建一个连接到SQL数据库的Windows服务,并检查表中的日期并将其与今天的日期进行比较,并更新该数据库中的字段,例如,如果日期等于今天的日期,则该字段将设置为true .
我遇到的问题是,当我启动服务时,它不会这样做但是当我以正常形式执行它时它完美地工作.
我的代码如下:
//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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*ten 10
另一种方法是等待事件而不是使用计时器.
即
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在您的服务中
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();
}
}
Run Code Online (Sandbox Code Playgroud)