轮询服务 - C#
有人能帮助我吗?
我正在创建一个连接到 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);
}
}
}
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.
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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种方法是等待事件而不是使用计时器。
即为
您服务
Another way of doing this would be to wait on an event rather then using a timer.
i.e.
In your Service
设置 Timer.AutoReset = true。否则它只会完成一次工作。但最好在 Windows 服务中使用线程。
[编辑]
啊,是的。默认情况下自动重置为 true。我也将其放入我的代码中:
GC.KeepAlive( myTimer );
因此,如果它处于非活动状态,GC 不会将其删除。
Set Timer.AutoReset = true. otherwise it will do its work only one time. but it's better to work with threading in windows services.
[edit]
ah, yes. autoreset is true in default. I put this too in my code:
GC.KeepAlive( myTimer );
so the gc won't remove it if it is inactive.