Run a process every x minutes or at time of day

Jose Cuervo

Member
Joined
Jul 14, 2010
Messages
14
Programming Experience
1-3
Hi,

What is the best way to run a process say every 30 minutes? Or at 0900?

I have an app which does quite a few things, and want to add something that will run every 30 minutes. Don't want to use windows scheduler as i want to keep it all in the one app.

Is the only way to run a thread.sleep for 1800000? If so, can i run 2 background workers on the 1 app?

Cheers :)
 
Add a Timer to your form and set its Interval appropriately. If you want to do something every 30 minutes then you'd set the Interval to 30x60x1000 milliseconds. If you want to do something at 0900 you'd determine the number of milliseconds until that time and set that as the Interval. You'd then handle the Tick event and do whatever, e.g. start a BackgroundWorker. Here's an example that will Tick at 0900 every day:
VB.NET:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.SetInterval()
        Me.Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Reset the Interval.
        Me.Timer1.Stop()
        Me.SetInterval()
        Me.Timer1.Start()

        'Do whatever.
    End Sub

    Private Sub SetInterval()
        Dim interval As TimeSpan

        If Date.Now.TimeOfDay > TimeSpan.FromHours(9) Then
            interval = Date.Today.AddHours(33) - Date.Now
        Else
            interval = Date.Now - Date.Today.AddHours(33)
        End If

        Me.Timer1.Interval = CInt(Math.Round(interval.TotalMilliseconds))
    End Sub

End Class
You can run as many BackgroundWorkers as you want. The BackgroundWorker uses the ThreadPool though so, if you have too many, some will get queued until some others have finished.
 
ok hit a small issue.

When i use the code
VB.NET:
    Private Sub TimerSetInterval()
        Dim interval As TimeSpan

        interval = Date.Now + Date.Today.AddMinutes(2)

    End Sub

i get the error that Value of type string cannot be converted to system.timespam

Any ideas? I dunno if this makes a difference but i am using WPF not VB forms. I did manage to add the timer though lol

Oh, i wont need to put this in a background worker will i? Will it leave my form free to do other things etc?
 
ok i am almost there, got it working kinda yey!

The only problem i have is getting it to run evey 10 minutes or so. I can get it to run from x length of time since the app was opened, but it wont repeate.

I assume i need some kind of loop?

Edit, nevermind i was being thick lol i had my textbox.text set to = and not += so it would write over itself and i would think it done nothing. Whopsie :)
 
Back
Top