如何有一个服务中每10分钟运行一个函数? [英] how to have a function run inside a service every 10 minutes?
本文介绍了如何有一个服务中每10分钟运行一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Windows服务运行,这里面我想运行函数中的每条然后分钟。
我已经发现了一些代码,但它似乎没有工作?
我有一个记录器,它似乎并没有进入timer_Elapsed功能不断?
保护覆盖无效的OnStart(字串[] args)
{
// SmartImportService.WebService.WebServiceSoapClient测试=新WebService.WebServiceSoapClient();
// test.Import();
log.Info(信息 - 服务指南);
_timer =新的定时器(10 * 60 * 1000); //每10分钟?
_timer.Elapsed + =新System.Timers.ElapsedEventHandler(timer_Elapsed);
}
私人无效timer_Elapsed(对象发件人,System.Timers.ElapsedEventArgs E)
{
log.Info(信息 - 检查时间);
的DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48);
如果(_lastRun< startAt&放大器;&放大器; DateTime.Now> = startAt)
{
//停止计时器
_timer.Stop();
试
{
log.Info(信息 - 导入);
SmartImportService.WebService.WebServiceSoapClient测试=新WebService.WebServiceSoapClient();
test.Import();
}
赶上(例外前){
log.Error(这是我的错误 - ,前);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}
解决方案
您需要启动定时器:
保护覆盖无效的OnStart(字串[] args)
{
日志.INFO(信息 - 服务指南);
_timer =新的定时器(10 * 60 * 1000); //每10分钟
_timer.Elapsed + =新System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); //< - 重要
}
I have a windows service running, inside this i want to run a function every then minutes. I have found some code but it doesn't seem to work? I have a logger and it does not seem to go into the timer_Elapsed function ever?
protected override void OnStart(string[] args)
{
// SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
// test.Import();
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.Info("Info - Check time");
DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
// stop the timer
_timer.Stop();
try
{
log.Info("Info - Import");
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) {
log.Error("This is my error - ", ex);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}
解决方案
You need to start the timer:
protected override void OnStart(string[] args)
{
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); // <- important
}
这篇关于如何有一个服务中每10分钟运行一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文