I am trying to kill excel automation process if it has been running for
more than 15 minutes. The script below is using two threads: thread 1 is
timer that will sleep for 15 minutes; and thread 2 will run the excel
automation.The script works fine except when there's an excel error
popup dialog box. When this happens, thread 1 fails to kill the excel
automation process (or it never reach that part of the script).

BTW, is there other way to accomplish this without using Thread.

require 'win32ole'
require 'win32/api'
include Win32

GetWindowThreadProcessId = API.new('GetWindowThreadProcessId', 'LP','L',
'user32')

threads = []
threads << Thread.new {
  sleep(15*60)            # Sleep for 15 minutes
  Thread.kill threads[1]  # Kill excel thread

  # Kill Excel process
  excel = Thread.current['excel']

  excel_pid = [0].pack('L')
  GetWindowThreadProcessId.call(excel.Hwnd, excel_pid)
  Process.kill('KILL', excel_pid.unpack('L')[0])
}
threads << Thread.new {
  # Start excel automation
  excel = WIN32OLE.new("excel.application")
  threads[0]['excel'] = excel

  excel['Visible'] = FALSE
  workbook = excel.Workbooks.Open('C:\\scripts\\Book1.xls')
  excel.Run('sample1')  # Run Excel macro, may fail and display error
message box
  excel.Quit()

  # Kill timer thread
  Thread.kill threads[0]
}

threads[0].join
threads[1].join
-- 
Posted via http://www.ruby-forum.com/.