Avatar of Zoldy2000
Zoldy2000
Flag for Canada asked on

how to introduce timer in my code vb.net

below is working code to listen for UDP message ..      what I need to do now is while it is listening introduce a timer that if it listens for 30 seconds and does not hear anything it executes some code then begins listening again resetting the timer.    Part of code below where I would like the timer.   Thanks in advance

While Not done
                    Console.WriteLine("Waiting for broadcast")
                    Dim bytes As Byte() = listener.Receive(groupEP)
                    Console.WriteLine("Received broadcast from {0} :", _
                        groupEP.ToString())
                    'Console.WriteLine( _
                    UDPMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length)
                    Console.WriteLine()
                    If UDPMessage.Contains(UDPMessagePart) Then
                        Proc = Process.GetProcessesByName("viewer")
                        If Proc.Count > 0 Then
                            GoTo SkipOpen
                        Else
                            Shell("c:\image.jpg")
                        End If
Visual Basic.NET

Avatar of undefined
Last Comment
Mike Tomlinson

8/22/2022 - Mon
Nasir Razzaq

>The Receive method will block until a datagram arrives from a remote host.

You will need to start the timer before that Receive call. Timer runs for 30 seconds and does the stuff that you want. If Receive returns before 30 seconds, it cancels the timer.
Zoldy2000

ASKER
you will need to elaborate with examples for me to understand what you are saying.    I am not an experienced programmer.
Nasir Razzaq

Add a timer to the form and set its interval

Change

Dim bytes As Byte() = listener.Receive(groupEP)

to

Timer1.Start
Dim bytes As Byte() = listener.Receive(groupEP)
Timer1.Stop


Timer1_Tick event:

Timer1.Stop
StuffThatYouWantToDoHere()
Timer1.Start
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Zoldy2000

ASKER
Thank you for your example.  

I am starting to the get the idea but where is the timer duration?    In my example 30 seconds?
John (Yiannis) Toutountzoglou

Hi ...
Take a look here.

Yiannis
Nasir Razzaq

Set that in properties of the timer control.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

As for the timer ...

interval of 30 seconds to timer (1sec = 1000)
timer1.Interval=30000
Zoldy2000

ASKER
Thank you everyone for your help.    I am still having some issues understand because of my limited knowledge.   I understand logically what we are doing but having trouble implementing.

How do I add the timer to my project.    its not form based it is console application.
John (Yiannis) Toutountzoglou

Declare a timer
 
Private WithEvents Tmr As New Timer

Open in new window

 Private Sub Tmr_Tick(sender As Object, e As System.EventArgs) Handles Tmr.Tick
.
.
.
.
        
Tmr.Stop()
 End Sub

Open in new window


Where You want to start the timer set:
 Tmr.Interval = 30000
 Tmr.Start()

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Zoldy2000

ASKER
Many of the examples given are not recognized.    Even Timer in Private statement is not recognized.    I am using VB Basic 2010 Express....    is that why?
John (Yiannis) Toutountzoglou

No it beacuse you are using Cosnole app..
sorry
use
Private Shared MyTimer As System.Timers.Timer

MyTimer = New System.Timers.Timer(30000)
and the handler
 AddHandler MyTimer.Elapsed, AddressOf OnTimedEvent

        MyTimer.Interval = 30000
        MyTimer.Enabled = True

also you can check
 Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub

http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Zoldy2000

ASKER
It will except this ... with this work for me.

            Dim Timer1 As New Timers.Timer
            Timer1.Interval = 30000

                    Timer1.Start()
                    Dim bytes As Byte() = listener.Receive(groupEP)
                    Timer1.Stop()
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Zoldy2000

ASKER
Sorry posted last post before reading yours I will test
John (Yiannis) Toutountzoglou

It is the same as yours ...
Zoldy2000

ASKER
Okay so I have this now


            Dim Timer1 As New Timers.Timer
            Timer1.Interval = 30000

                    Timer1.Start()
                    Dim bytes As Byte() = listener.Receive(groupEP)  (does not step past here)
                    Timer1.Stop()

But it does not do anything ... it still sits on listener after 30 seconds.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Zoldy2000

ASKER
So think my problem is this code.

Dim bytes As Byte() = listener.Receive(groupEP)

What I think I need is to do this for 30 seconds if nothing received run some code and start over ....

If something is received my existing code should work...

is that right?  If so how can I do this?
Mike Tomlinson

Since Receive() is blocking, and can't be cancelled, you need to put it into its own Thread and then call Abort() against it to kill it.  So when your Timer fires you Abort() the Thread (cancelling the Receive() call), run your "timer" code, then create a new Thread to Receive() again, and restart the Timer.  Whenever Receive() actually gets something, you restart the Timer.
John (Yiannis) Toutountzoglou

Dim myTimer As New System.Timers.Timer()
        AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf OnTimer)
        myTimer.Interval = 30000
        myTimer.Enabled = True
        myTimer.AutoReset = False

Open in new window

stopreceiving
Public Shared Sub OnTimer(ByVal source As [Object], ByVal e As ElapsedEventArgs)
...Abort
        MessageBox.Show("30 seconds Elapsed..")

    End Sub

Open in new window


Sory for delay...Dauhgter is playing on lap..

Hello Mike...
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Zoldy2000

ASKER
ElapsedEventHandler is not supported
Zoldy2000

ASKER
I am more confused then when I started. lol...  Here is what i am currently working with.

            Dim Timer1 As New Timers.Timer
            Timer1.Interval = 30000
            Timer1.Enabled = True

            Try
                While Not done
                    Console.WriteLine("Waiting for broadcast")
                    Timer1.Start()
                    Dim bytes As Byte() = listener.Receive(groupEP)
                    Timer1.Stop()
John (Yiannis) Toutountzoglou

try changing
   AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf OnTimer)
With
  AddHandler myTimer.Elapsed, AddressOf OnTimer
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Zoldy2000

ASKER
AddHandler myTimer.Elapsed, AddressOf OnTimer  

OnTimer no recongnized
SOLUTION
John (Yiannis) Toutountzoglou

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Zoldy2000

ASKER
Ontimer is not declared
Zoldy2000

ASKER
I think I need to start over fresh as even if I fix the error this is still not making sense to me.

I want to listen for UDP message for say 30 seconds in our example.

If I don't here anything run some code and start again.

If I do here something run some other code and start again.

Maybe this will help?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

dim you add this
Public Sub OnTimer(ByVal source As [Object], ByVal e As ElapsedEventArgs)
'Abort here..
        Console.WriteLine("30 seconds Elapsed..")

    End Sub

Open in new window

Zoldy2000

ASKER
Okay I have it running now ..... ...  it seems to do the first 30 second but does not restart...    Looking at it now
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Zoldy2000

ASKER
The original suggested code is working partially so not ready to start over just yet but thank you for your suggestion.

Currently if I change the code to autoreset = true it works until the listener hears a UDP message and my other code runs.    When that happens the timer seems to get messed up and fires randomly.    

30 seconds Elapsed starts appear after just a few seconds over and over.

Here is what I have in the main part of the code.

 While Not done
                    Console.WriteLine("Waiting for broadcast")

                    Dim myTimer As New System.Timers.Timer()
                    AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf OnTimer)
                    myTimer.Interval = 30000
                    myTimer.Enabled = True
                    myTimer.AutoReset = True

                    Dim bytes As Byte() = listener.Receive(groupEP)

                    Console.WriteLine("Received broadcast from {0} :", _
                        groupEP.ToString())
                    'Console.WriteLine( _
                    UDPMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length)
                    Console.WriteLine()
                    If UDPMessage.Contains(UDPMessagePart) Then
                        Proc = Process.GetProcessesByName("viewer")
                        If Proc.Count > 0 Then
                            GoTo SkipOpen
                        Else
                            Shell("c:\Viewer.exe c:\image.jpg")
                        End If
Your help has saved me hundreds of hours of internet surfing.
fblack61
Mike Tomlinson

With that model you have NO way of aborting the Receive() call...so while the Timer will fire at your interval, it can't do anything useful from there.

You need to move that Receive() call to a different thread so it can be aborted when the Timer fires.

Look at my code...  ;)
Mike Tomlinson

Also, you're creating a wiring up a NEW timer with each iteration of the while loop.  That should be done outside the loop! (so only one timer is created)

I suppose you could setup your code like below...

Note how after Receive() we call myTimer.Stop(), and then after processing the message we call myTimer.Start().
                Dim myTimer As New System.Timers.Timer()
                AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf OnTimer)
                myTimer.Interval = 30000
                myTimer.Enabled = True
                myTimer.AutoReset = True

                While Not done
                    Console.WriteLine("Waiting for broadcast")
                    Dim bytes As Byte() = listener.Receive(groupEP)
                    myTimer.Stop()

                    Console.WriteLine("Received broadcast from {0} :", _
                        groupEP.ToString())
                    'Console.WriteLine( _
                    UDPMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length)
                    Console.WriteLine()
                    If UDPMessage.Contains(UDPMessagePart) Then
                        Proc = Process.GetProcessesByName("viewer")
                        If Proc.Count > 0 Then
                            GoTo SkipOpen
                        Else
                            Shell("c:\Viewer.exe c:\image.jpg")
                        End If
                    End If

                    myTimer.Start()
                End While

Open in new window

*BUT...this means it would be possible for the both the timer code and the receive code to run AT THE SAME TIME,  since the timer could fire and start, but then a message could come in before the timer code finishes.
Zoldy2000

ASKER
I tried your code and it works great...    thank you so much will award points shortly..   I can open another support case unless this is something simple.     I am using the following code to close a program called viewer.    But it does not recognize the .kill....    according to what I read this should work.  

Proc2 = Process.GetProcessesByName("viewer")
Proc2.kill
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Mike Tomlinson

GetProcessesByName() returns an ARRAY of Process since many apps can have more than one instance running.

To kill it:
Proc2 = Process.GetProcessesByName("viewer")
If Proc2.Length > 0 Then
    Proc2(0).Kill
End If

Open in new window

*This assumes just one instance would be running, and it kills that first instance.
Mike Tomlinson

*Also, Kill() should be a last resort if the app has a GUI.

Instead, try CloseMainWindow() first:
Proc2 = Process.GetProcessesByName("viewer")
If Proc2.Length > 0 Then
    Proc2(0).CloseMainWindow()
End If

Open in new window

Zoldy2000

ASKER
The code does not work.    at least it does not close the application.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Mike Tomlinson

Try this out:
        Dim Proc2() As Process
        Proc2 = Process.GetProcessesByName("viewer")
        For i As Integer = Proc2.GetUpperBound(0) To 0 Step -1
            Proc2(i).Kill()
        Next

Open in new window


Are you sure that "viewer" is correct?  That should be the name of the executable itself, without any path or extension.
Zoldy2000

ASKER
This works

Proc2 = Process.GetProcessesByName("viewer")
If Proc2.Length > 0 Then
    Proc2(0).kill()
End If
Mike Tomlinson

Yay!
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.