System.Timers.Timer线程查询

时间:2014-02-28 15:06:41

标签: vb.net multithreading service timer smtp

我正在尝试编写一个监视它的时间的系统服务。当它达到设定的时间时,它将触发包含来自数据库的数据的电子邮件。

我已经实现了以下代码,该代码创建了一个system.timers.timer对象,并为已过去的事件添加了一个处理程序。然后,使用if statemnt将指定时间与系统时钟进行比较。如果该陈述为真,则生成电子邮件

问题1 if语句在到达正确的时间时不会触发。我假设这是因为系统时钟与指定的时间不完全匹配。是否可以允许范围确保系统时钟与指定时间匹配

问题2 如果我将if语句上的匹配类型更改为“If now> Email Time”,则if语句将运行。然而,每次定时器到达间隔时,它每100ms运行一次if语句。如果我理解正确,这将在一个单独的线程中运行事件的每个实例。有没有办法将它限制为一个线程,这样会在IF语句中间停止处理计时器事件

导入System.Net.Mail 进口系统 Imports System.Timers

Public Class Service1     Dim MyTimer As New System.Timers.Timer()     受保护的覆盖Sub OnStart(ByVal args()As String)         '在此处添加代码以启动您的服务。这个方法应该设置一些东西         “在运动中,所以你的服务可以完成它的工作。

    Console.WriteLine("OnStart")


    AddHandler MyTimer.Elapsed, AddressOf OnTimedEvent

    ' Set the Interval to 10 seconds (10000 milliseconds).
    MyTimer.Interval = 1000
    MyTimer.Enabled = True



End Sub

Protected Overrides Sub OnStop()
    ' Add code here to perform any tear-down necessary to stop your service.
    Console.WriteLine("OnStop")
    Timer1.Stop()

End Sub

Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
    Console.WriteLine("OnTimerEvent!")

    Dim EmailTime As DateTime = #12:20:00 PM#


    If Now > EmailTime And Now < EmailTime Then
        Dim MyLog As New EventLog() ' create a new event log 
        ' Check if the the Event Log Exists 
        If Not Diagnostics.EventLog.SourceExists("QEDService") Then
            Diagnostics.EventLog.CreateEventSource("QEDService", "QEDService Log") ' Create Log 
        End If
        MyLog.Source = "MyService"
        ' Write to the Log 
        Diagnostics.EventLog.WriteEntry("QEDService Log", "This is log on " & _
        CStr(TimeOfDay), EventLogEntryType.Information)


        Try
            Dim Smtp_Server As New SmtpClient
            Dim e_mail As New MailMessage()
            Smtp_Server.UseDefaultCredentials = False
            Smtp_Server.Credentials = New Net.NetworkCredential("email", "password")
            Smtp_Server.Port = 587
            Smtp_Server.EnableSsl = True
            Smtp_Server.Host = "smtp.gmail.com"

            e_mail = New MailMessage()
            e_mail.From = New MailAddress("This is a test message subject")
            e_mail.To.Add("alex@qedscaffolding.com")
            e_mail.Subject = "Email Sending"
            e_mail.IsBodyHtml = False
            e_mail.Body = "This is a test message body"
            Smtp_Server.Send(e_mail)
            MsgBox("Mail Sent")

        Catch error_t As Exception
            MsgBox(error_t.ToString)
        End Try
    End If


End Sub

结束班

0 个答案:

没有答案