vb.nettimerscheduled-taskswindows-task-scheduler

Don't know how to run a Function at a specific time


I tried to learn more but sadly I can't understand how it works with the Windows Task Scheduler, so I tried something simple, but it still doesn't work.

I want this function to run every day except the weekends.

Here is my code:

Sub automaticworkdayinsert()

    If Timer4.Interval = 7200000 Then
        Dim time As Date = Date.Now
        Dim currhour As Integer
        Dim currminute As Integer
        Dim ReportHour As Integer
        Dim ReportMinute As Integer
        currhour = time.Hour
        currminute = time.Minute
        ReportHour = 15
        ReportMinute = 10
        If currhour = ReportHour AndAlso currminute = ReportMinute Then
            insertAndcheckWorkday(False)
        End If
    End If
End Sub

Solution

  • It's a bit hard to tell by what you included with your code (you should probably also include the code in the insertAndcheckWorkday function), but as far as:

    And i am not sure why but i want the hour to be 03 but vs turn it automatically at 3.

    Have a look at:

    https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    In your case, you'd either want to use hh (12 hr format) or HH (24 hr format).

    Also, for comparing dates/times there's a handy function built-into the framework already:

    https://learn.microsoft.com/en-us/dotnet/api/system.datetime.compare?view=netcore-3.1

    Last thing, this doesn't answer your question, but my OCD :p just wants to help ya out a bit:

    Sub automaticworkdayinsert()
    
        If Timer4.Interval = 7200000 Then
    
            Dim time As Date = Date.Now
    
            Dim currhour As Integer = time.Hour
            Dim currminute As Integer = time.Minute
            Dim ReportHour As Integer = 15
            Dim ReportMinute As Integer = 10
    
            If currhour = ReportHour AndAlso currminute = ReportMinute Then insertAndcheckWorkday(False)
    
        End If
    
    End Sub
    

    The above changes will make the code easier to read in the long run, as well as initialize the vars immediately with a specific value (arguably, since Integers already get initialized as 0 it might be sort of moot, but generally considered good coding practice anyway). Also, if you've only got 1 thing happening after an if you can place it on one line as well. Again, easier for reading down the road.