我有一个与 Magento API 通信以提取数据的 Windows 服务。Windows 服务如何在第一次启动时正常运行,没有任何错误或问题。包含轮询器,用于计算下一次执行 Windows 服务的时间,并在配置文件中指定键值“pollerExecutionTime”。我注意到的是,尽管将 Windows 服务设置为自动启动类型,但它并没有在预定时间启动。这是轮询器的代码。如果有人可以看看并告诉我我做错了什么,那将非常有帮助,因为我不精通调试 Windows 服务。
private DateTime _nextExecutionTime;
public DateTime NextExecutionTime
{
get {
//if(_nextExecutionTime!=null)
// return _nextExecutionTime;
return _nextExecutionTime = GetNextExecutionTime(Convert.ToDateTime(ConfigurationManager.AppSettings["pollerExecutionTime"]).TimeOfDay, DateTime.Now.AddDays(1).DayOfWeek);
}
set {
_nextExecutionTime = value;
}
}
protected override void OnStart(string[] args)
{
DebugMode();
try
{
System.Threading.Thread.Sleep(10000);
if (!StartService())
{
Stop();
}
}
catch (Exception exception)
{
_logEntryError.Message = "OnStart: Cannot start the service due the following reason " + exception.Message + Environment.NewLine + exception.InnerException + Environment.NewLine + exception.StackTrace;
Logger.Write(_logEntryError);
}
//StartService();
}
private bool StartService()
{
_timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
_timer.Interval = 10000; //First time after 10 sec
_timer.Enabled = true;
_timer.AutoReset = true;
_logEntryStart.Message = "Execution of CheckLongtimePendingRequestsAndDelegate Method -- STARTED";
_logEntryEnd.Message = "Execution of CheckLongtimePendingRequestsAndDelegate Method -- ENDED";
return true;
}
protected override void OnStop()
{
}
[Conditional("DEBUG_SERVICE")]
private static void DebugMode()
{
Debugger.Break();
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TimeSpan difference = NextExecutionTime.Subtract(DateTime.Now.Date);
_timer.Interval = difference.TotalMilliseconds;
try
{
Logger.Write(_logEntryStart);
_svc.GetOrderList();
_svc.GetCustomerList();
_svc.GetInvoiceList();
}
catch (Exception exception)
{
_logEntryError.Message = "Error by invoking the WebMethods Method : " + exception.Message + Environment.NewLine + exception.InnerException + Environment.NewLine + exception.StackTrace;
Logger.Write(_logEntryError);
}
}
public static DateTime GetNextExecutionTime(TimeSpan time, DayOfWeek targetDayOfWeek)
{
var date = new DateTime(
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
time.Hours,
time.Minutes,
time.Seconds).AddDays(GetDaysToNextWeekDay(DateTime.Now, targetDayOfWeek));
return date;
}
/// <summary>
/// Gets the days to next week day.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="targetDayOfWeek">The target day of week.</param>
/// <returns></returns>
/// <remarks></remarks>
public static int GetDaysToNextWeekDay(DateTime startDate, DayOfWeek targetDayOfWeek)
{
int start = (int)startDate.DayOfWeek;
int target = (int)targetDayOfWeek;
if (target <= start)
target += 7;
return target - start;
}