【发布时间】:2022-01-09 04:29:51
【问题描述】:
您好,我在程序中编写了一个调用 Rest Api 并获取一些信息的方法。 我想每分钟都打电话。我填写了 OnStart 和 OnStop 以及我的方法所在的所有 timer_Elapsed。我安装我的服务并启动它,但它只是第一次运行,如果有人知道解决方案可以帮助我,永远不会再重复。提前谢谢你
开始时:
protected override void OnStart(string[] args)
{
///just for log to show program is working
ayandehBLL.Save_Log("Service started...", nameof(OnStart));
if (timer == null)
{
timer = new Timer();
timer.AutoReset = true;
timer.Interval = 3000; //*
Convert.ToDouble(ConfigurationManager.AppSettings["IntervalMinutes"]);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
}
protected override void OnStop()
{
timer.Stop();
timer.Enabled = false;
ayandehBLL.Save_Log("Service stoped", nameof(OnStop));
//WriteErrorLog("Test window service Stoped");
}
-----------------------------
private void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
var a = ayandehBLL.GetProductCode();
ayandehBLL.Save_Log($"Request national code is {a}", "test");
if (a != null)
{
Request_DOM request = new Request_DOM();
request.ProductCode= a;
try
{
var result = ayandehBLL.GetMyProductInfo(request);
if (result != null)
{
ayandehBLL.Save_Log(JsonConvert.SerializeObject(result), nameof(OnStart));
}
else
{
ayandehBLL.Save_Log("GetMyProductInfo() returned null", nameof(OnStart));
}
}
catch (Exception ex)
{
ayandehBLL.Save_Log(ex.Message.ToString(), "OnElapsedTime");
}
}
else
{
ayandehBLL.Save_Log("Request national code is null", "OnElapsedTime");
}
//WriteErrorLog("OnElapsedTime done");
}
【问题讨论】:
-
您配置服务的方式很好。但是,我认为在第一次执行处理程序 timer_Elapsed 之后出现错误。您能否向我们提供日志,以便我们找出问题所在?
-
我没有任何错误,我用 windows 窗体测试它并生成数据,我在 time_elapsed 中复制 button_click 事件中的代码。
-
当您在 Windows 中签入服务时,您的服务是仍在运行还是已停止?
标签: c# api methods timer windows-services