跟踪一组任务的已用时间

时间:2014-10-09 20:26:22

标签: vb.net timer stopwatch elapsedtime

我正在尝试编写一个小型的VB.NET应用程序,以便在工作中进行交叉团队研究。我需要能够为单个任务运行多个计时器,并且当用户完成任务时,他们可以结束它并将其存储在CSV文件中。我可以一次完成单个任务,这已经在业务中运行了一段时间。让multipul任务一次运行的最佳方法是什么。我有想法将任务添加到列表视图并将双击事件作为结束任务功能。但是我似乎无法让计时器独立运行。有人可以帮忙吗?这有意义吗?

这是此课程中主要的工作量。如果这没有意义我提前做道歉。我不是一个贸易程序员,这只是我在工作中练习的一种爱好。

另一件事是将经过的秒数计算在内,我可以用标签做到这一点,但理论上我需要一个不受限制的任务......

Public Class runningTask
    Dim timenow As DateTime = Now
    Dim elapsed
    Dim localTask = GlobalVars.task

    Public Sub AddItem()
        CreateTimer()

        Dim str(3) As String
        Dim itm As ListViewItem

        str(0) = localTask
        str(1) = timenow
        str(2) = elapsed

        itm = New ListViewItem(str)

        frmTime.lvTimers.Items.Add(itm)
    End Sub

    Private Sub CreateTimer()
        Dim tmr As New Timer
        tmr.Interval = 1000
        tmr.Enabled = True
        AddHandler tmr.Tick, AddressOf GlobalTimerTick
    End Sub

    Private Sub GlobalTimerTick(ByVal sender As Object, ByVal e As EventArgs)
        Dim t As TimeSpan = Now - timenow
        elapsed = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", Math.Floor(t.TotalHours), t.Minutes, t.Seconds, t.Milliseconds)
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

我采用了更多的OOP方法,就Timers来说可能更经济,但界面非常简单。核心是一个跟踪作业和时间的TaskItem,然后是一个集合类来公开它们,启动它们并停止它们。通过在尽可能低的水平上尽可能多地隐藏功能,事情会变得更简单。

我只使用了一个计时器,无法理解为什么单个任务需要多个计时器。如果TaskItem在启动时记录DateTime(这在我的创建时会自动发生),那么您根本不需要任何计时器。 Elapsed始终使用StartedTimeDateTime.Now(针对正在运行的任务)或CompletedTime计算已完成的任务。我无法看到Timer添加任何内容的位置。

你必须为你的目的制作许多mod。这不会保存已完成的项目,也不会从列表中删除它们,但可能会为您提供一个起点。它也是第一关的东西;这里和那里肯定存在问题。

Imports System.Collections.ObjectModel

Public Class Tasks

    ' slight overkill
    Private Enum LVGroups
        Running
        Completed
    End Enum

    Public Enum TaskJobs
        SweepFloor
        BuildRobot
        CleanOven
        RepairRobot
        EmptyTrash
        TeachRobotToTalk
        MakeCoffee
        TeachRobotToWalk
        WashDishes
        TeachRobotVisualBasic
    End Enum

    ' class for a single task
    Public Class TaskItem
        ' these ought to be readonly; so no cheating
        Public Property ID As String
        Public Property EmpName As String

        Public Property StartedTime As DateTime
        Public Property CompletedTime As DateTime

        ' or job code...
        Public Property Job As TaskJobs

        ' put in a ClassLib or Namespace
        Friend Sub New(sName As String, tj As TaskJobs)
            EmpName = sName
            Job = tj

            StartedTime = DateTime.Now
            CompletedTime = DateTime.MaxValue
            ID = System.Guid.NewGuid.ToString
        End Sub

        Public Function IsActive() As Boolean
            Return (CompletedTime = DateTime.MaxValue)
        End Function

        Public Sub EndTask()
            CompletedTime = DateTime.Now
        End Sub

        Public Function GetElapsed() As String
            Dim t As TimeSpan
            If IsActive() Then
                t = DateTime.Now - StartedTime
            Else
                t = CompletedTime - StartedTime
            End If
            Return String.Format("{0:00}:{1:00}:{2:00}", Math.Floor(t.TotalHours),
                                                 t.Minutes, t.Seconds)
        End Function

        Public Overrides Function ToString() As String
            Return String.Format("{0} {1} {2}", EmpName, Job.ToString, GetElapsed)
        End Function

    End Class


    Private col As Collection(Of TaskItem)

    Private myLV As ListView

    ' assign the LV when tasks are created
    Public Sub New(lvTask As ListView)
        myLV = lvTask
        col = New Collection(Of TaskItem)
    End Sub

    ' add new task with EmpName and JobCode
    Public Sub NewTask(sName As String, tj As TaskJobs)

        Dim ti As New TaskItem(sName, tj)
        col.Add(ti)

        ' LV layout: empname, job, elapsed, ID
        ' but only 3 columns so that ID is "hidden"

        Dim lvi As New ListViewItem(ti.EmpName)
        lvi.SubItems.Add(ti.Job.ToString)
        lvi.SubItems.Add(ti.GetElapsed)
        lvi.SubItems.Add(ti.ID)

        lvi.Group = myLV.Groups(LVGroups.Running.ToString)
        myLV.Items.Add(lvi)

    End Sub

    ' called from dbl click on a running task item
    Public Sub StopTask(lvi As ListViewItem)

        Dim ti As TaskItem = (From t In col Where t.ID = lvi.SubItems(3).Text).First

        ' the form doesnt check the status, so we must
        If ti.IsActive Then
            ti.EndTask()
            lvi.Group = myLV.Groups(LVGroups.Completed.ToString)
        End If

    End Sub

    ' called from the form timer tick event
    Public Sub UpdateDisplay()
        Dim ti As TaskItem

        ' iterate items to get ID of runners
        For Each lvi As ListViewItem In myLV.Groups(LVGroups.Running.ToString).Items
            ' ToDo add error checking

            ti = (From t In col Where t.ID = lvi.SubItems(3).Text).First
            lvi.SubItems(2).Text = ti.GetElapsed

        Next

    End Sub

    Public Function RunnersCount() As Integer
        Return GetActiveList.Count
    End Function

    Public Function GetCompletedList() As List(Of TaskItem)
        ' long form
        Dim tList As New List(Of TaskItem)

        For Each ti As TaskItem In col
            If ti.IsActive = False Then
                tList.Add(ti)
            End If
        Next

        Return tList

        ' short form
        'Dim list = (From t In col Where t.IsActive = False).ToList
    End Function


    Public Function GetActiveList() As List(Of TaskItem)
        ' long form
        'Dim tList As New List(Of TaskItem)

        'For Each ti As TaskItem In col
        '    If ti.IsActive Then
        '        tList.Add(ti)
        '    End If
        'Next   
        'Return tList

        ' short form
        Dim list = (From t In col Where t.IsActive).ToList
        Return list

    End Function
End Class

用法:

Public Class Form1

    Private myTasks As Tasks

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        myTasks = New Tasks(Me.lvTask)
        cboTask.Items.AddRange([Enum].GetNames(GetType(Tasks.TaskJobs)))
    End Sub

添加任务:

myTasks.NewTask(cboEmp.Text, CType(cboTask.SelectedIndex, Tasks.TaskJobs))

停止任务:

' called from LV mousedoubleclick, so determine the item
Dim lvi As ListViewItem = lvTask.GetItemAt(e.X, e.Y)
myTasks.StopTask(lvi)

显然,停止任务可能会自动将数据附加到导出文件。该功能将在任务集合类中,它将在从集合中删除任务之前完成(可选 - 只要您可以从已完成的任务中告知活动,它们不会伤害任何事物。)

计时器勾选事件:

    myTasks.UpdateDisplay()

enter image description here

最后,打开Option Strict,特别是因为人们会根据项目的输出做出决定。