2010-03-30 82 views
2

所有,我有一个自定义对象,我用VB.NET(.net 2.0)编写。该对象实例化自己的threading.timer对象,并执行一些后台进程,包括根据数据库中检测到的数据,通过smtp通过定期询问oracle数据库和发送电子邮件。以下是Windows服务类Windows服务难题

Public Class IncidentManagerService 
'Fakes 
Private _fakeRepoFactory As IRepoFactory 
Private _incidentRepo As FakeIncidentRepo 
Private _incidentDefinitionRepo As FakeIncidentDefinitionRepo 
Private _incManager As IncidentManager.Session 

'Real 
Private _started As Boolean = False 
Private _repoFactory As New NHibernateRepoFactory 
Private _psalertsEventRepo As IPsalertsEventRepo = _repoFactory.GetPsalertsEventRepo() 
Protected Overrides Sub OnStart(ByVal args() As String) 
    ' Add code here to start your service. This method should set things 
    ' in motion so your service can do its work. 
    If Not _started Then 
     Startup() 
     _started = True 
    End If 

End Sub 

Protected Overrides Sub OnStop() 

    'Tear down class variables in order to ensure the service stops cleanly 
    _incManager.Dispose() 
    _incidentDefinitionRepo = Nothing 
    _incidentRepo = Nothing 
    _fakeRepoFactory = Nothing 
    _repoFactory = Nothing 

End Sub 

Private Sub Startup() 
    Dim incidents As IList(Of Incident) = Nothing 
    Dim incidentFactory As New IncidentFactory 

    incidents = IncidentFactory.GetTwoFakeIncidents 
    _repoFactory = New NHibernateRepoFactory 
    _fakeRepoFactory = New FakeRepoFactory(incidents) 
    _incidentRepo = _fakeRepoFactory.GetIncidentRepo 
    _incidentDefinitionRepo = _fakeRepoFactory.GetIncidentDefinitionRepo 

    'Start an incident manager session 
    _incManager = New IncidentManager.Session(_incidentRepo, _incidentDefinitionRepo, _psalertsEventRepo) 
    _incManager.Start() 

End Sub 

End Class 

实施实验的一点点我来到位于OnStart方法上面的代码后的代码。所有功能都通过了从VS2005部署到我的开发PC上的测试,但是当部署在真正的目标计算机上时,该服务将无法启动并响应以下消息:

“本地计算机上的服务已启动,然后停止.. 。“

我是否正在以这种正确的方式去做?如果不是,我怎么才能在Windows服务类的范围内最好地实现我的事件管理器。对事件管理者实施定时器似乎毫无意义,因为这已经实现了自己的定时器...

任何帮助非常感谢。

亲切的问候

的Paul J.

+0

Betcha你在服务器上的nhibernate配置是错误的。除此之外,抛出一些日志记录,以便找出导致它失败的原因。 – Will 2010-03-30 16:25:03

+1

另外,在服务中使用计时器可能不是很好的设计。如果您的服务只按照计划活动,那么它应该是一个计划任务。服务应该总是在应用程序上。 – Will 2010-03-30 16:26:26

+0

请问,该进程每两秒轮询数据库以获取新数据。我会尝试在服务类中加入一些额外的日志记录,看它是否显示任何有用的东西。感谢您的意见。 – 2010-03-31 09:23:21

回答

1

我有几个建议。

首先,Windows服务必须能够在设定的时间段内成功启动(默认情况下我认为是30秒)。您收到的错误消息并没有指出这是一个问题,但您可能需要在服务的OnStart中启动一个快速计时器,并在TimerElapsed事件处理程序中启动启动过程。这将保证服务每次启动。

其次,正如在一些评论中提出的那样,您必须将日志记录添加到您的应用程序。每个好的服务都应该有能力记录一切有助于追踪问题的东西。大多数常见的日志记录框架将允许您设置不同的详细级别,因此当事情运行良好时,日志会更小。