一个基本的调度程序






2.64/5 (5投票s)
为程序定义计划,
引言
我需要一个简单的调度器,在准确的时间/时间跨度内执行,以生成自动报告。 我检查了各种文章和互联网,寻找一个可以完全按要求执行的调度器,如果失败,则在最近的下一个时间执行。
背景
在搜索互联网时,我发现了一篇由Andy Brummer撰写的文章,它为我提供了很多关于代码的想法,但是我需要更简单的东西,所以它没有解决我的目的。 此外,我正在使用VB.NET进行编程,而提供的代码是用C#编写的,这总体上会使我难以实现。
在我们继续之前,如果您可以阅读有关delegate
、调用和存储的内容,这将很有帮助。我建议您阅读Abhishek Khanna关于delegate
的一篇好文章。它是VB.NET中一个非常重要的补充,并简化了许多问题。
我还建议您阅读Microsoft Library - MSDN中关于委托的文档,这是一个非常有用的指南,可以解决很多编程问题。
逻辑
整个代码块都包含在一个名为Scheduler
的类中。它依赖于三个对象,即
System.Windows.Forms.Timer
System.Collections.ArrayList
System.Data.DataTable
DataTable
用于存储期间发生的所有事件。 这样做是为了允许立即更改值。 我曾尝试使用ArrayList
和其他集合对象,但没有得到正确的结果。
SetSchedule.Columns.Add(New DataColumn("SchType", System.Type.GetType("System.String")))
SetSchedule.Columns.Add(New DataColumn
("exeTime", System.Type.GetType("System.DateTime")))
SetSchedule.Columns.Add(New DataColumn("active", System.Type.GetType("System.Boolean")))
SetSchedule.Columns.Add(New DataColumn
("NextexeTime", System.Type.GetType("System.DateTime")))
SetSchedule.Columns.Add(New DataColumn
("TimeDiff", System.Type.GetType("System.TimeSpan")))
我向DataTable
添加了这五个字段,用于跟踪计划,并且我枚举了以下内容
Public Enum Scheduled
Once = 1
BySecond = 2
ByMinute = 4
ByHour = 8
Daily = 16
Weekly = 32
Monthly = 64
Yearly = 128
Regular = 256
End Enum
我使用ArrayList
来存储所有要执行的与scheduler
匹配的事件。
Using the Code
将类项目添加到您的解决方案,并在您的项目中引用它。
声明一个变量,如下所示
Dim sch As New Scheduler.Scheduler
声明并将您的delegate
分配给函数和Sub
'Declare a Delegate without Parameters
Delegate Sub ShowMessage()
'Declare a Delegate With Parameters
Delegate Sub ShowMessageBox(ByVal str As String)
'Define a Sub/Function without Parameters
Private Sub DisplayMessage()
RichTextBox1.Text += "It is time: " + Now.ToString + vbCrLf
End Sub
'Define a Sub/Function with Parameters
Private Sub DisplayMessageBox(ByVal str As String)
MsgBox("It is time: " + Now.ToString)
End Sub
'Pass a Delegate without Parameters
Dim msd As ShowMessage = AddressOf DisplayMessage
'Pass a Delegate with Parameters
Dim msd1 As ShowMessageBox = AddressOf DisplayMessageBox
设置scheduler
计时器
'Add a Schedule to Do the Events On a Particular Date/Time
sch.AddSchedule(Now)
'Add a Schedule to do the Events, after every Time Span
sch.AddSchedule(New TimeSpan(0, 5, 0))
'Add a Schedule to do the Events, after every Time Span starting from Date/Time
sch.AddSchedule(#5/28/2008 4:00:00 AM#, New TimeSpan(0, 5, 0))
'Add a Schedule to do the Events, EveryDay at the Said Times in 24Hrs Clock
sch.AddSchedule("09:25", "21:25")
声明event
sch.AddEvent(msd)
sch.AddEvent(msd1, "Test String")
Start
scheduler
sch.Start()
历史
- 2008年5月28日:首次发布
联系我
如果您在使用代码时遇到任何问题,可以通过dfdosabhai@gmail.com或我的IM(即时通讯)dfdosabhai@yahoo.com与我联系