Avatar of Zoldy2000
Zoldy2000Flag 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
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

>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.
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

you will need to elaborate with examples for me to understand what you are saying.    I am not an experienced programmer.
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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?
Hi ...
Take a look here.

Yiannis
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Set that in properties of the timer control.
As for the timer ...

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

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.
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

Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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?
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
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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()
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

Sorry posted last post before reading yours I will test
It is the same as yours ...
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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.
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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?
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.
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...
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

ElapsedEventHandler is not supported
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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()
try changing
   AddHandler myTimer.Elapsed, New ElapsedEventHandler(AddressOf OnTimer)
With
  AddHandler myTimer.Elapsed, AddressOf OnTimer
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

AddHandler myTimer.Elapsed, AddressOf OnTimer  

OnTimer no recongnized
SOLUTION
Avatar of John (Yiannis) Toutountzoglou
John (Yiannis) Toutountzoglou
Flag of Greece image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

Ontimer is not declared
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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?
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

Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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
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...  ;)
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.
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

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
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.
*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

Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

The code does not work.    at least it does not close the application.
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.
Avatar of Zoldy2000
Zoldy2000
Flag of Canada image

ASKER

This works

Proc2 = Process.GetProcessesByName("viewer")
If Proc2.Length > 0 Then
    Proc2(0).kill()
End If
Yay!
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo