Wednesday 19 September 2007

Is it idle?

The number of things that we run when a machine boots or user logs in continues to grow and boot times are an issue. RSS Bandit is a case in point and on my machine Bandit introduces a 45s delay to boot time.

I wrote a vbscript that waits for 5 minutes before running Bandit and replaced the Bandit run command in the registry with my script. This works well enough if the machine has done with all the startup events within 5 minutes. What if it hasn't? So I created this routine that will detect idle time on the computer.

function WaitForIdle(timeout, delay, unit)
dim objWMIService, colItems, idleCounts, idleTime, objItem, startDate
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")

WaitForIdle = false

startDate = now
idleCounts = 0
' measure the idle time across processors every second until n consecutive measures are above 93 or timeout occurs
do until idleCounts >= 10 or DateDiff(unit, startDate, now) >= timeout
WScript.sleep 1000
Set colItems = _
objWMIService.ExecQuery("SELECT PercentIdleTime FROM Win32_PerfFormattedData_PerfOS_Processor where name<>'_Total'", _
"WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

if colItems.count >= 1 then
idleTime = 0
for each objItem in colItems
idleTime = idleTime + objItem.PercentIdleTime
next
idleTime = idleTime / colItems.count
if idleTime >= 93 then
idleCounts = idleCounts + 1
else
idleCounts = 0
end if
end if
WScript.Echo "Last idle: " & idleTime & ", count: " & idleCounts
loop

WScript.Echo "count: " & idleCounts & ", timeout: " & (DateDiff(unit, startDate, now) >= timeout)

if idleCounts >= 10 then
WaitForIdle = true
startDate = now
do until DateDiff(unit, startDate, now) >= delay
WScript.sleep 1000
loop
end if
end function

Wscript.Echo Now

if WaitForIdle(30, 10, "s") then
WScript.Echo "Done."
else
WScript.Echo "No can do."
end if

Wscript.Echo Now
The unit is the unit for the timout and sleep and is the value used by the datediff vbscript function - "s" = seconds, "n" = minutes. The function returns true if the computer was idle, false otherwise.

Sample output:

19/09/2007 10:43:23
Last idle: 32.5, count: 0
Last idle: 54, count: 0
Last idle: 98, count: 1
Last idle: 73, count: 0
Last idle: 95, count: 1
Last idle: 82.5, count: 0
Last idle: 96.5, count: 1
Last idle: 94.5, count: 2
Last idle: 52.5, count: 0
Last idle: 98, count: 1
Last idle: 65, count: 0
Last idle: 24.5, count: 0
Last idle: 91.5, count: 0
Last idle: 100, count: 1
Last idle: 93, count: 2
Last idle: 42, count: 0
Last idle: 79, count: 0
Last idle: 82, count: 0
Last idle: 90, count: 0
Last idle: 100, count: 1
count: 1, timeout: True
No can do.
19/09/2007 10:43:54

No comments: