我有一个与Magento API通信的Windows服务来提取数据。 Windows服务如何在第一次启动时正常运行,没有任何错误或问题。 有一个poller合并,它计算下一次执行windows服务和键值" pollerExecutionTime"在配置文件中指定。我注意到,尽管将Windows服务设置为自动启动类型,但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;
}