【问题标题】:Block timer if execution is not completed如果执行未完成,则阻塞计时器
【发布时间】:2014-01-03 10:09:42
【问题描述】:

这是处理我的服务的类:

Imports System.Timers
Imports System.Configuration

Public Class Service
    Private _lastRun As DateTime = DateTime.Now
    Private ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

    Protected Overrides Sub OnStart(ByVal args() As String)
        log.Info("Service started.")

        Dim timer As New System.Timers.Timer(1 * 60 * 1000)
        AddHandler timer.Elapsed, AddressOf timer_Elapsed
        timer.Start()
    End Sub

    Private Sub timer_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs)
        Dim now As DateTime = DateTime.Now
        If now.Minute > _lastRun.Minute Then
            Dim m As New Main()
            m.Main()
            m = Nothing
        End If
        _lastRun = now
    End Sub

    Protected Overrides Sub OnStop()
        log.Info("Service is stopped")
    End Sub
End Class

一分钟后,Main 方法被执行。 Main 方法的运行时间是不可预测的。如果执行时间超过一分钟,则执行另一个 Main 方法。我会禁止这种行为,所以如果Main 方法仍在运行Main 方法的新实例,则必须禁止。我能做些什么?

【问题讨论】:

  • 将 AutoReset 属性设置为 False,使其仅触发一次。在 Elapsed 事件处理程序结束时调用 Start() 以使其再次触发。

标签: vb.net timer windows-services


【解决方案1】:

定义你的计时器对象,使其在类中具有作用域:

private _timer As New System.Timers.Timer(1 * 60 * 1000)

然后当计时器结束时,禁用它直到你完成你的 Main 方法:

Private Sub timer_Elapsed(sender As Object, e As System.Timers.ElapsedEventArgs)
    _timer.Enabled = False
    Dim now As DateTime = DateTime.Now
    If now.Minute > _lastRun.Minute Then
        Dim m As New Main()
        m.Main()
        m = Nothing
    End If
    _lastRun = now
    _timer.Enabled = True
End Sub

【讨论】:

  • 我自己达成了一个不同(但相似)的解决方案。我已将 Main 方法调用包装在 timer.stop()/timer.start() 中,即使您的解决方案看起来更优雅,此解决方案也能完成工作。
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
相关资源
最近更新 更多