I have a program that occasionally needs to scan some directories recursively (an improvement for this part of the program is in the pipeline, but won’t be ready for a while). To avoid the user having to wait for this scanning, I would like to do the scanning while the user isn’t using my program when possible.
I intend to implement it by running a timer that checks for idle time. I’ve found the following for checking system idle time:
http://www.delphitips.net/2007/11/11/how-to-detect-system-idle-time/
This would be functional, but I would prefer to activate the function even when the user is working with other programs on the same computer. This way, if he switches to another program, I could catch up on the scanning I need to do.
I realize that I could do the scanning in a background thread, and either that or some sort of windows hooks will be implemented at some point, but not just yet.
EDIT:
The goal here is a relatively easy change to the program to do any scanning that might be queued while the user isn’t actively using MY application. The scanning isn’t especially intensive, but it isn’t done in a thread, and therefore freezes my app while in progress. Basically, I’m looking for a quick win while I’m working on a more long term solution.
Use the
Application.OnIdleevent. That event is triggered when your program has no more window messages to handle. The keyboard and mouse both generate messages, so if there are no more messages, then the user is not using your program, even if it has the focus.As long as
Doneis False and there are no messages in the queue, your program will continue to call that event handler, allowing you to find more files. When the user generates some input, your program will handle the messages before callingOnIdleagain.When you’ve finished scanning the file system, set
Doneto True so that the program stops re-calling theOnIdlehandler. If you neglect to do that, then your program will use all available CPU time repeatedly calling an event handler that does nothing.For this to work, you’ll need to use a non-recursive search routine. A recursive search will search the whole file system before returning, but if you do that, then the
OnIdlehandler will hang your program, which is the oposite of what you want. You can use a queue of directory names, and each time the event is fires, pop one item off the queue, search it, and add its contents to the end of the queue.