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.
Related
Some sub's in my VB.Net program take a lot of time, and I do not understand why. I'd like to start a counter at the beginning of the sub and write the Milliseconds passed for each row in the console.
I tried using a Timer and resetting it after each row but it was too threadintesive. Is there a better way, using the system date/time in order to get a quite precise reading of the time each step takes?
Thank you
Use the Stopwatch class. However doing so for each row seems a bit impossible... That means you would have to add for example Console.WriteLine() after every row.
Example usage:
Dim sw As New Stopwatch
sw.Start()
yourMethod()
sw.Stop()
Console.WriteLine(String.Format("{0} ms", sw.Elapsed.TotalMilliseconds))
This is my first time using VBA in Outlook so please bear with me
I've created a basic Macro that does various things to folders. Since this takes a while I decided to make a status window that says what its currently doing. I simply keep setting one of the label's values with this
Function UpdateStatus(Message As String)
StatusForm.StatusUpdate.Caption = Message
StatusForm.Repaint
End Function
The issue is that after it runs for a bit (5-15 seconds) the window and the rest of outlook locks; the form no longer updates and has a "(Not Responding)" in its window title.
I feel like I'm somehow dead locking the UI thread but I'm at a loss on how to work around it. Commenting out Repaint not surprisingly doesn't let it update at all, but outside of that I don't know where to look
Any suggestions?
Try adding DoEvents in your computationally intensive loop. This yields the executing code to the UI thread so that other things can get done when you have computationally intensive stuff going on in the background. Office is single-threaded, so you can block the UI when you are running macros.
Sample:
Sub LockUI()
Dim x
x = Timer
Do While Timer - x < 5
'Blocks the UI for 5 seconds
Loop
End Sub
Sub LockUI2()
Dim x
x = Timer
Do While Timer - x < 5
'Doesn't block the UI
DoEvents
Loop
End Sub
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.
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
So I'm kind of new to VB and am just playing around with a little project, I currently need a loop that is constantly checking the systems clock to see if it's equal to a certain time.
While Not myTime.Hour = 24
If TimeOfDay = newTime Then
nfi.ShowBalloonTip(15)
intRandNumb = RandomNumber(1, 15)
dblAddMinutes = intTime + intRandNumb
newTime = TimeOfDay.AddMinutes(dblAddMinutes)
End If
End While
I have this right now, but obviously it's grinding everything to a halt and using 50% of my cpu in the process, I just would like to know what I can substitute in or change to make this loop run better and perform how I need it to.
you can add
Threading.Thread.Sleep(0),
this will cause a context switch and greatly reduce the CPU usage
Also consider using a timer object to be called every 10 or 100 ms, this will also be better in usage then having a loop
You can use
Threading.Thread.Sleep(0)
This will cause the working thread to yield the rest of it's current timeslice which will reduce the cpu usage quite a bit. However you should consider whether you really nead busy waiting for the time or if you could get away with setting a timer to count down the difference between the current time and the expected time, e.g.:
var t = new System.Timers.Timer((DateTime.Now - DateTime.Now).TotalMilliseconds);
t.Elapsed = DoSomething;
t.Start();
checking the systems clock to see if it's equal to a certain time.
There are two "correct" ways to do this:
Build a normal app that doesn't care what time it is, and set it up in windows as a schedule task.
Check the time once and calculate how long until the desired time. Then set up a timer to wait for that exact duration.
Under no circumstance should you keep polling the system clock for something like this that will just run once.
As Joel pointed out, you should try using a timer instead. I'm not sure if your app is a form or console or other, so I'll try to be generic and use System.Timers.Timer.
The code here (interval is set at 10ms, change to a value of your need):
Private timer1 As System.Timers.Timer
Const interval As Integer = 10
Sub initTimer()
timer1 = New System.Timers.Timer(10)
AddHandler timer1.Elapsed, AddressOf Me.timer_Elapsed
timer1.Start()
End Sub
Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
'do your stuff here
'Console.WriteLine(e.SignalTime.ToString())
End Sub