VB.Net Asp.Net Web Forms - Unable to create a Scheduled job


#1

Here’s a test page I created. All of the form elements on the aspx page are valid. It’s basically two test buttons and a label. One button tries to schedule a change to the label text. The other resets the schedule button. Here is the code behind:

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load        
    End Sub

    Protected Sub TestScheduler()
        Using server = New BackgroundJobServer()
            BackgroundJob.Schedule(Function() UpdateLabel(), TimeSpan.FromSeconds(10))
        End Using
    End Sub

    Sub BtnHangfire_Click(ByVal sender As Object, ByVal e As EventArgs)
        btn_Test_Hangfire.Enabled = False
        TestScheduler()
    End Sub

    Sub BtnHangfireReset_Click(ByVal sender As Object, ByVal e As EventArgs)
        btn_Test_Hangfire.Enabled = True
        lblAsync.Text = "Reset Hangfire!"
    End Sub

    Function UpdateLabel()
        lblAsync.Text = "I am scheduling a job."
        Dim result = True
        Return result
    End Function

When I try and click on the button, the button disables fine. Approx 10-20 seconds later I see the job attempt and it shows:

System.NullReferenceException: Object reference not set to an instance of an object.
HangFireTest.aspx.vb:line 30
' Which is lblAsync.Text = "I am scheduling a job."

#2

This was a silly mistake on my part. The issue was that the label hasn’t been initialized from a background task. Therefore, it was causing an error, as correctly reported.

I was able to create a test that successfully updated a notifications table in my DB:

Public Function WriteNotification()
    Try
        Dim notification = "I succeeded in scheduling a notification"
        Dim sql_statement = "INSERT INTO sys_notifications (message) VALUES ('" & notification & "')"
        InsertIntoDB(sql_statement)
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

So, for those reading using a similar setup, this function above replaces the updatelabel portion. The InsertIntoDB is just a sub I created that does an insert into my DB.