How can I show a running timer in a label? - vb.net

my question here is how can i show a running timer consisting of minutes and seconds that is being imported from a SQL database. I have already imported it but then how can i display the timer in labels?
sqlq = "Select Duration from XYZ where ID = 20"
sda = New SqlDataAdapter(sqlq, conn)
sda.Fill(ds)
_timer = ds.Tables(0).Rows(0).Item("Duration")
Timer1.Interval = _timer * 60000
Timer1.Enabled = True
Timer1.Start()

The Timer1_Tick event will fire every time the interval expires. IE, if ds.Tables(0).Rows(0).Item("Duration") = 2, and you set the interval to be _timer * 60000, since interval is in milliseconds, it will fire every 2 minutes.
This does not mean something is going to run for the next 2 minutes, it means the 2 minutes from now, the Timer1_Tick event will fire, than 2 minutes later it will fire again, and so on.
Seems like you are trying to run a timer, every second, for 2 minutes (in this case). You should set the interval to 1000 (1 second) and set some variable Private iCountDown as int32 in your form. The set it to the number of seconds you want it to run iCountDown = _timer * 60. Now start your timer, Timer1.Start.
Now, every send the tick event will fire. In this event you want to decrement the loop so you are counting down. iCountDown -= 1 and set your label text. Just make sure that when the countdown hits 0 that you stop the timer If iCountDown <= 0 then Timer1.Stop
One note, the timer runs on the UI thread so if you do not have any pumping (idle time) in your UI thread, the Tick even will not fire as expected.
Hope that helps you understand what is going on with timers.

Related

What is 1 interval in the timer VB (What is 1 interval in normal time)

I am making a program that has a timer inside of it. I want the timer to be able to display milliseconds so I used the timer from the tool bar in VB and I fiddled around with the intervals but I cant get it to measure 1 millisecond.
I have searched around a lot and I could not find anything useful accept one thing called System.Timers.Timer but I cant figure out how to use it. So could someone tell me what number of intervals = 1 millisecond and what System.Timers.Timer is and how to use it.
For help helping me:
In my code the timer adds one to a variable called mili every time it ticks and then displays that in a text box. When mili = 1000 it adds one to a variable called seconds and when seconds hits 60 it does the same for minuets.
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
mili = mili + 1
If mili = 1000 Then
mili = 0
second = second + 1
lblsec.Text = second
Thanks in advance.

How to slow down timer in VB.NET?

I am making a HTML tester. I added the following code to timer.
Dim sb As New System.Text.StringBuilder
sb.AppendLine(RichTextBox1.Text)
IO.File.WriteAllText("htmltester.html", sb.ToString())
WebBrowser1.Navigate("file:///" & IO.Path.GetFullPath(".\htmltester.html"))
But it reloads very fast and makes annoying sound. Is there any way to slow down the timer to execute this command after 5 seconds ?
Thanks !
You can refer the timer Class. Timer's tick is controlled by setting the interval property.so make its interval to 5000 if you want to repeated it in every 5 seconds. since the interval is measured in Milli seconds.
you can set the interval by using the following code,
Let's assume that the name of the timer is SlowTimer:
SlowTimer.Interval = 5000
Your code does not have any timing functions in it or any loops so it should just run once.
If this is just some hacky throw away code then try a Threading.Thread.Sleep(5000) before the navigate.

Dynamically assigning the timer interval

I have a function that needs to be run for every 15 minutes using the timer in VB.net.
But the challenge present here is, if i start the timer, say at 2:00 AM, the actual function will be executed at 2:15 AM after which the same function will be executed for every 15 mins.
I have a sub "Timer" in which the timer is started and the Addhandler operator calls the "ONhandler" function for every 15mins.
private mytimer as timer
private sub Timer()
{
with mytimer
.autoreset=true
.enabled=true
.interval=900000
.start
end with
AddHandler mytimer.elapsed ,assressof onhandler
console.readkey()
}
onhandler(byval source as oblject,byval e as elapsedeventargs)
{
Performs the DB operations.
}
Initially I had a couple of logic that would start the timer exactly at every 00,15,30,45th mins of each and every hour. Assuming that I start the application at 1:55AM, the logic would ensure that the applications sleeps till it reaches 2:00AM and at 2:00 AM, the timer would start. After 15 mins, i.e 2:15AM, the function will get executed.
But what I need is , I dont want my application to wait for 15 mins from 2:00 till 2:15. Instead it should process at 2:00 and then start the timer. To overcome this, I had included a new function "onhandler" with same name of AddHandler method which does the same process.
private sub Timer()
{
onhandler() ****New function namesd as AddHandler method
with mytimer
.autoreset=true
.enabled=true
.interval=900000
.start
end with
AddHandler mytimer.elapsed ,assressof onhandler
console.readkey()
}
onHandler()
{
Do same DB function
}
After implementing the new logic,
if I start the application at 1:55 AM, my app would sleep till 2:00 AM after which the Onhandler() method inside sub will get executed first and it would get completed at 2:01Am.
Now the timer is started for 15 mins and the the next set of process is executed at 2:16AM as the timer is set for a 15 min interval. But I need my process to run exactly at 2:15AM. In other words, the timer interval must be for 14mins and not 15 mins.
another example is, I start the application at 3AM and if it ends at 3:03Am, then the time must have an interval of 12 mins and not 15 mins, for the next run.
IS there any way to make the timer interval dynamic for each and every time the process gets completed based on the process ending time???
PS : I am new to DotNet and have been cracking my head on this issue for the past few days. Guys, kindly help me out here.
Thanks in advance,
Madhu.
The correct way to do this would be to run a Windows Task at specific times. But if you really want to write this in your application, you could wake your program every minute to check the time and just add this to the called method:
Dim d = DateTime.Now
if(Not (d.Minute = 0 OrElse d.Minute = 15 OrElse d.Minute = 30 OrElse d.Minute = 45)) Then
Return 'Quits if the current time is not right
End If
I had something similar once. I would have a variable called NextExecutionTime which would contain the next time the process need to be executed.
At first it would be (example) 2am.
I would then have a timer every minute and if the current time was equal or greather than NextExecutionTime, I would execute the process and setup the NextExecutionTime variable to the next time I wanted the process to run.

Timer is Off, code possibly taking too long to compile before it ticks?

I'm using a Threading.DispatcherTimer and every tick of the timer runs a subroutine.
Is it possible that if the subroutine takes longer then 1s for the processor to finish that it will mess up the time of the timer that is counting in seconds?
Try
timercount = Nothing
timercount = New DispatcherTimer()
timercount.Interval = TimeSpan.FromSeconds(1)
timercount.Start()
AddHandler timercount.Tick, AddressOf TickMe 'Every Second the 'TickMe' Method runs
Catch ex As Exception
' MessageBox.Show(ex.Message)
End Try
Private Sub TickMe()
CL(0).Actual = H.Actual
TextBoxSerialNumber.Focus()
IntSec = IntSec + 1
H.ActualBoxTime = H.ActualBoxTime.AddSeconds(1)
CL(0).ActualBoxTime = H.ActualBoxTime
If IntSec Mod 60 = 0 Then
H.Actual = H.Actual + 1
CL(0).Actual = H.Actual
End If
CL(0).TargetBox = H.TargetBox
PopulateCutGrid(CL)
End Sub
I've found after 50-60 minutes of counting it's off by almost 10 minutes!
From the MSDN article regarding DispatchTimer:
Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
If you need something more precise, I would recommend System.Threading.Timer. Each time the method of this timer is invoked, a ThreadPool thread is used. From this article:
The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.
Also forgot to mention that you'll need to use Invoke and InvokeRequired for WinForms or Dispatcher for WPF (I think, since I don't use WPF).
Edit 1:
Regarding your comment about needing total seconds, you can just store the original DateTime somewhere, and total seconds would be calculated using (DateTime.Now - StoredDateTime).TotalSeconds(). I would also recommend reading this article about threading in WPF to see if it applies in your case.
Edit2:
Actually, since I think the only thing you're after is a precise count of elapsed time, you could use a Stopwatch to keep track of time. Try using the regular DispatchTimer and just refer to the stopwatch each "tick" of that timer. That way, the Stopwatch is what keeps track of time, not the timer that could be used just for updating the UI.

Console app timer to call web methods every x minutes

I am coding in VB.Net, VS 2008.
I wrote a console app that consumes 2 web methods from a web site application. I need to enhance this console app so that it launches the web methods continuously, perhaps every x minutes (during business hours), but never before the last invocation has terminated, whose duration may vary, depending on how many accounts there are to process.
Originally, I scheduled the application using Task Scheduler, but I think this doesn't prevent two invocations at the same time.
Although I have seen many posts on using timers, I haven't found exactly what I need.
So far I have:
Dim aTimer As New System.Timers.Timer()
AddHandler aTimer.Elapsed, AddressOf TriggerWebMethods
' Set the Interval to 10 minutes:
aTimer.Interval = 1000 * 60 * 10 '(1 second * 60 = 1 minute * 10 = 10 minutes)
aTimer.Enabled = True
aTimer.AutoReset = True
When should Timer.Elapsed be used vs. Timer.Tick?
What is the difference between Timer.Enabled vs Timer.Start, and should I be selecting just one?
I would like the 2nd web method to kick off when the first one is done.
I'd like to keep this as simple as possible. Thank you for all help.
If you are dealing with a System.Timers.Timer, then you'd only have the Elapsed event available. If a System.Windows.Forms.Timer, then you'd use the Tick event. You're not writing a WinForms app so you would be using the System.Timers.Timer.
Personally, I would only use the Enabled property to see if the timer has been started. I wouldn't use it to start or stop it. Using the Start() or Stop() method makes it very clear what's happening to the timer.
If your web methods execute synchronously, you could just call them one after the other in your TriggerWebMethods() method. The second will not be called until the first completes.
Sub TriggerWebMethods(source As Object, e As ElapsedEventArgs)
FirstWebMethod()
SecondWebMethod()
End Sub
If asynchronously, you'd have to register a callback on the first web method to execute the second when it completes. In VB, I believe you can use the second directly as the callback, depending on how you make the asynchronous call. (Sorry, my VB is very rusty now so might not be 100% correct syntax)
Sub FirstWebMethod()
' ...
End Sub
Sub SecondWebMethod()
' ...
End Sub
Sub TriggerWebMethods(source As Object, e As ElapsedEventArgs)
Dim first As Action = AddressOf FirstWebMethod
first.BeginInvoke(AddressOf SecondWebMethod, first)
End Sub
Just to add a little to Jeff M's answer. The Timer.Elapsed Event has the following note.
If the SynchronizingObject property is null, the Elapsed event is
raised on a ThreadPool thread. If the
processing of the Elapsed event lasts
longer than Interval, the event might
be raised again on another ThreadPool
thread. In this situation, the event
handler should be reentrant.
Since you're in a Console app you can either hand roll you own SynchronizingObject or you can set the AutoReset to False, and change your TriggerWebMethods to have a start at the end. You may even want to offset the interval to take into consideration the amount of processing time.
e.g.
Dim start As Date = Now
'do stuff
Dim ts As TimeSpan = Now - start
Dim i As Integer = (1000 * 60 * 10) - ts.TotalMilliseconds
Dim aTimer As Timers
aTimer.Interval = i