vb.net console in a do loop - vb.net

I've written a fairly simple console app to check an Exchange email box every 30 seconds. When it's not running the check routine, it's in an empty do/loop in the Main method just to keep the program running. I find that that is taking a whole lot more of the server's resources (around 50%) than I expected.
Here's the Main method:
Sub Main()
GetSettings()
tmrCheckInterval.Interval = 30000
tmrCheckInterval.Start()
WriteToConsole("Scan app started")
Do
Loop
End Sub
I don't do very many console apps, so I am not sure if this is the most efficient way, and I have struck out with a Google search. Is there an alternative process that will keep the app running without consuming resources?
Thanks...

If you only want this to run every 30 minutes, you are much better off removing the loop entirely and instead setting up a Scheduled Task.
But as to why this code uses so much CPU... the program is doing work. It has a tight loop that never stops and never yields the CPU. It sits near 50% because you have a dual-core CPU and this uses all of one core. If you had a quad-core, it would use 25%. In the bad old single core days, this would use all of the CPU and even bringing up the task manager to kill the app could be challenging. I'm gonna have nightmares tonight remembering those times, so thanks for that.
I know it seems like you set an interval in this code, but that interval only applies to the timer, and is not part of the loop body. You want something more like this:
Sub Main()
GetSettings()
WriteToConsole("Scan app started")
Do
'Remove the timer and call it's elapsed code directly here.
Thread.Sleep(30 * 60 * 1000)
Loop
End Sub
And again, this is still not as good as just using a scheduled task.

Related

How to stop the user moving the console window in vb.net

I'm currently taking computer science A-Level so it should be obvious how to do this as I have been using VB.Net for a year already. However, I have developed a console application which uses the threading.thread.sleep() function to keep track of timings. This is so far the best way I have found to do so but after some destructive testing I have found when the user drags the console around quickly this slows the program down and causes the timings to be wrong. So, is there any way to stop the user from moving a console window, essentially keeping the location of the console fixed, in vb.Net? I'm currently using Visual Studio 2015.
Many Thanks,
Dan
Although it may be possible to stop the window being dragged, it is the wrong approach. Sleeping a thread is not an accurate way of maintaining timing data.
Moving the window is not the only action on a windows system that will slow the application down and you're beginning to interfere with the standard windows experience.
I assume you have code that increments the amount of delay after each sleep.
Instead: To maintain accuracy you should store the value of DateTime.Now when the application starts timing.
dim mStartTime = DateTime.Now
And then get the time differences relative to this.
dim elapsedMilliseconds = (DateTime.Now - mStartTime).TotalMilliseconds
All timers / sleep rountines are subject to timing error due to system priority / loads. This approach will prevent those errors accumulating.
Modifying the console is not easy from .net (you need to use the windows api), however it's pretty simple to prevent the user from doing this if you're using winforms. Maybe you could change your application type.

Interrupt, stop or timeout LotusScript Agent internally

I would like to timeout a LotusScript agent internally. The Agent Manager has a timeout of 60 min with one task, which is needed for some agents. In my case the agent normally runs 7 - 10 min, but it might hang on opening a mail calendar profile. It just hangs, does nothing but consuming CPU and blocking other agents from running.
Is there any way to stop/interrupt the agent internally, so that I can set a timeout of 30 sec for that operation and if it does not succeed stop the agent?
Problematic Code Snippet:
Set notesDocument = notesDatabase.GetProfileDocument("calendarprofile")
Error on the Mail Server short time after the problem (other server than the agent server)
SchedMgr: Error processing calendar profile document (NoteID: NT00000902) in database XXXX/XXXX.nsf: Document has been deleted
Understanding internally as without external agent, process and so on.
If no operation is blocking, you can instanciate timer, check periodically if your time is comsumed and end graccefullly your code.
If your code is blocked (as in your example) on an operation, there is nothing you can do: no preampt task, no interruption.
I had the same issue when using ole to write in Excel. When a dialogue box were openend in Excel the task (run by http) just stoped forever. The max time execution even don't work.
As per #Emmanuel's answer, I don't believe you can do anything to set a timeout on the operation that is hanging. However, since you know about the problem you might be able to work around it using the NotesNoteCollection class. I.e., something like this:
dim c as NotesNoteCollection
set c = db.CreateNoteCollection(false)
c.selectProfiles = true
c.BuildCollection
Then you loop through the collection using id=c.getFirstNoteId and id=c.getNextNoteId(id) in a pattern similar to what you use to loop through a regular NotesDocumentCollection, retrieving each profile document using doc =db.GetDocumentByID(id) and checking with doc.isValid to make sure it's not a deletion stub (which seems to be the root of your problem), and then checking if it is the calendarprofile by calling doc.getItemValue("$Name") and examining the value in the 0th element of the value array. It's a string containing a prefix "$profile" followed by an underscore, a number (three digits, always?), and then the profile doc name and another underscore. (In some profile docs, $Name would also contain a username, which IIRC occurs after the second underscore, but that's not the case with the calendarprofile doc. Use NotesPeek to examine a mail database to see the format.) Then, once you've verified that the document exists and is not a stub, go ahead and use db.getProfileDocument to assure that you're working on the cached version of the note.
You might also want to investigate why your code is hanging. I've not run into a situation like this before, but I'm wondering if there might be an excessive number of deletion stubs in the database and your code is triggering some sort of cleanup operation on them that is taking a very long time. That's just a guess, but this behavior isn't normal and even though I believe you can work around it, that might not be true. It's just a guess. And building and iterating the NotesNoteCollection might even trigger the same bad behavior for all I know.

My.Application StartUp event

I am rewriting an application for printing shipping labels that we have been using for many years, because over those many years, many programmers have added bits and pieces to it, and it has become harder and harder to maintain.
While considering design choices, I came across catching the application's StartUp event in ApplicationEvents.vb, which I thought would be a good choice for this application because the main form is only displayed if there are more than 10 labels to print at a time (displays a progress bar if so, but mostly it does one label at a time and as such the progress bar isn't desired).
Now, whether this is a good choice I'm not sure, but while playing around with it I have found a need to exit the application from this event if certain criteria aren't met (invalid command line args, network directory not found in expected location, and a few other criteria). I have been unsuccessful in figuring out how to exit from the application if something like the above were to occur. The only thing close I have found is setting the StartupEventArgs.Cancel to True, but the documentation states that this only stops the main form from loading and if set to true should point code on a different processing path.
Is there a "proper" way to exit the application in the StartUp event? I've tried using My.Application.Shutdown which doesn't exist, and RaiseEvent ShutDown() which gives the error "Derived classes cannot raise base class events."
Linked here is the main doc I have been using for research (and the related links on the linked page):
https://msdn.microsoft.com/en-us/library/t4zch4d2(VS.80).aspx
You can use End to immediately kill the process, note that:
This will prematurely kill the process
Any files being written to can become corrupted
Any other activity related to the program will be terminated
To protect against file corruption, you could use a subroutine that 'finishes up' and then terminates the program, for example:
Private Sub finishUp()
[..close files, forms, here..]
End
End Sub
I did this myself for a gameserver program I made a couple of months ago; the program needed to note in the SQL database the startup and shutdown times. I made it log the shut-down time in a subroutine similar to the one above.
Note that the same subroutine could (and probably should) be used when you need the program to close at any other time.

Continuous Loop/Repeat causes Excel to Crash (after hours/days)

I have some VBA code that runs every 15 minutes continually. This code runs fine at first but after a period of time (which varies from around 4 hours to 5 days) Excel crashes.
It is not a VBA crash (with debug option) but it is Excel freezing and saying the application needs to be restarted.
Am I trying to use Excel in a way it was not designed for? Should I be clearing some memory/cache to avoid this?
I believe it is due to a fail of the OnTime method of the application, I had your same problem some time ago with an Excel tool which was scraping data from the web every 5 minutes. Sometimes it just crashed with no specific log or error/warning. Here is the workaround I have implemented:
1) In the Workbook_Open event I have put :
myMacro 'the call to my procedure when the workbook is opened
ThisWorkbook.Save 'I was saving the results, I don't know if you need this
ThisWorkbook.Close 'I was closing my Workbook
2) In the Windows system, I was using a tool (installed usually with the system) called Task Scheduler, whose executable lies into the system folder (C:\Windows\System32\taskschd.msc) and it's really intuitive and easy-to-use. I have scheduled a task every 5 minutes which consisted on opening the workbook (once this was done, the open-workbook-event macro was triggered so my procedure was called, and after its execution the Workbook was closed and saved with the two lines of code I have posted you above).
Even if this is just my opinion (that I cannot prove with technical evidences), I don't trust too much the Application.OnTime in the long-term; it works fine for a little task every 10 seconds for a few minutes, but when the macro should be running regularly and you want to avoid seeing that, once every 5 hours, the Excel process crashes... then I would suggest to let the scheduling task to the Microsot tool rather than to the Excel application method.
MY EXPERIENCE
- my Excel, with the OnTime method in the macro, was crashing in a period between 1 hour (minimum crash) and 7 hours (maximum length of time before crashing). I was forced to open a distance connection from home and running it in the morning before to go out, to make sure the job was done before I got at work.
- my same macro, with the procedure I have described you above, never crashed anymore. I believe the system process is much more reliable than the Excel's one (but again, I don't have any evidence to prove you this so don't take it as gold).

Repeat a task with time delay in WinJS

I am developing an app in WinJS and I need to periodically run some tasks with a constant and specified delay between each pair of executions.
In particular, I am intending to update the user's position on the map every 30 seconds.
I am not quite sure how to implement the task scheduler in WinJS. I have looked at the background task class, but that doesn't seem to be much help in my case.
If Im reading this correctly and you simply want to do this while the application is running you just need a javascript timer - setTimeout.
note that with setTimeout you pass in the function itself without parenthesis, not a string name. Here's an app sample with a timer that updated the UI, although the main important takeaway here is that you need to make sure you call setTimeout again from within your 'update' function. Check out that code here
If you want some sort of background task to do this and generate a separate image (I dont think thats what you ant, but I'll include that since we're talking about tasks and delays)
If you are using Windows 8.1 (which releases soon) you can use the new scheduler class and pause and resume every 30 seconds as shown here
If you are using Windows 8 (and will work on 8.1) you can if I recall correctly setup your scheduled tasks every fifteen minutes and create one shot tasks for each 30 seconds within that time. run background task on timer