i wan set a timer in my program to execute a certain function daily,weekly or monthly(which will decide by the user)!User also can execute manually the certain function at anytime!

any1 can teach me how 2 do these 2 function in my program?

thanks............

Dani AI

Generated

is right: keeping a UI app or ASP.NET site alive for weeks just to hit a date is fragile. If you can, move the work into a console app or Windows Service and let Windows Task Scheduler invoke it. Still, if you must keep it inside your VB.NET app, avoid polling the clock every minute (as showed). A more reliable pattern is a single self-rescheduling timer that always computes the next wall-clock run (daily/weekly/monthly), fires once, runs your code, then re-arms itself. That also makes manual runs trivial because you call the same method the timer calls.

Here is a compact VB.NET example using System.Threading.Timer that supports daily, weekly (e.g., every Monday at 08:00), and monthly schedules without busy-waiting:

' Fields set from user choices
Private _timer As Threading.Timer
Private _freq As Frequency
Private _timeOfDay As TimeSpan
Private _dow As DayOfWeek   ' for weekly
Private _dom As Integer     ' for monthly (1..31)

Private Enum Frequency : Daily : Weekly : Monthly : End Enum

Public Sub StartScheduler()
    ScheduleNext()
End Sub

Private Sub ScheduleNext()
    Dim now = DateTime.Now
    Dim nextRun = ComputeNext(now)
    Dim due = nextRun - now
    If _timer Is Nothing Then
        _timer = New Threading.Timer(AddressOf OnTick, Nothing, due, TimeSpan.FromMilliseconds(-1))
    Else
        _timer.Change(due, TimeSpan.FromMilliseconds(-1))
    End If
End Sub

Private Function ComputeNext(now As DateTime) As DateTime
    Select Case _freq
        Case Frequency.Daily
            Dim t = New DateTime(now.Year, now.Month, now.Day).Add(_timeOfDay)
            If t <= now Then t = t.AddDays(1) : Return t
        Case Frequency.Weekly
            Dim t = New DateTime(now.Year, now.Month, now.Day).Add(_timeOfDay)
            Dim delta = (CInt(_dow) - CInt(now.DayOfWeek) + 7) Mod 7
            t = t.AddDays(delta) : If t <= now Then t = t.AddDays(7) : Return t
        Case Frequency.Monthly
            Dim d = Math.Min(_dom, DateTime.DaysInMonth(now.Year, now.Month))
            Dim t = New DateTime(now.Year, now.Month, d).Add(_timeOfDay)
            If t <= now Then
                Dim n = now.AddMonths(1)
                d = Math.Min(_dom, DateTime.DaysInMonth(n.Year, n.Month))
                t = New DateTime(n.Year, n.Month, d).Add(_timeOfDay)
            End If
            Return t
    End Select
    Return now
End Function

Private Sub OnTick(state As Object)
    Try
        RunJob()   ' your SMS/report logic
    Finally
        ScheduleNext()
    End Try
End Sub

Public Sub RunNow()
    RunJob()
End Sub

Tips:

  • Persist the next scheduled time (or last successful run) so if the app restarts after the target time, you can run immediately and then reschedule.
  • Recalculate from wall-clock each time to handle DST shifts. Avoid fixed millisecond intervals for long periods.
  • If this is ASP.NET, do not rely on in-process timers because app pools recycle. Host the job in a service or scheduled console, and call the same RunJob() used by the manual button.

Recommended Answers

All 10 Replies

Hopefully you may want not a windows program running, waiting for a timer during one month.

The best way is to isolate this functionalty in a separate console application and use the task scheduler of Windows to planify when, and under wich user, must be executed.

Be aware that this console application can not have any interactive screen or message, as is running in batch, and should end gently.

Hope this helps

.

i wan design a program that have a timer to execute certain code(like send sms) at certain period.
The period is select by user(daily,monthly,weekly) and user oso can execute this certain code manually at anytime when user wan.
who can provide the code that how to set this timer?

Thanks

Dim WithEvents MyTimer as System.Timers.Timer ' to define the timer at module or class level
'
' inside de sub where you define when to fire the timer
'
Dim NumberOfSecondsToFiretheTimer As Double = 86400D ' One Day
MyTimer.Interval = NumberOfSecondsToFiretheTimer
MyTimer.Start

To catch the event

Private Sub MyTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles MyTimer.Elapsed
'
'  do whatever you need
' 
End Sub

i think, if your program running everyday, you can use timer event tick,then set interval, then the event you need just insert in that tick

if i wan the code execute at every monday(8am),how i nid to do?
thanks....

Use the windows task scheduler
http://support.microsoft.com/kb/308569/en-us for XP
http://windows.microsoft.com/en-US/windows-vista/Schedule-a-task for Vista
http://support.microsoft.com/kb/814596/en-us for Windows 2003
Also maybe you are interested on http://msdn.microsoft.com/en-us/library/aa383614(v=vs.85).aspx for the task scheduler API and http://msdn.microsoft.com/en-us/library/aa384006(v=vs.85).aspx showing examples about task scheduler API usage.

Hope this helps

may i got some code sample for this function?
it is bcoz i wan write the code in the program that i design so can generate a report every monday(8am).
Thanks.....
it's urgent...

You could use a timer control that constantly checks the time and when the time matches 8:00 it will run your code. An example in vb.net is below. iIuse something similar to run a SQL Backup Utility I created.

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        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 = 08
        ReportMinute = 00
        If currhour = ReportHour AndAlso currminute = ReportMinute Then
            RunReport()
        End If
    End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.