threaded.rb 1007 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. require 'thread'
  2. require 'huginn_scheduler'
  3. STDOUT.sync = true
  4. STDERR.sync = true
  5. def stop
  6. puts 'Exiting...'
  7. @scheduler.stop
  8. @dj.stop
  9. @stream.stop
  10. end
  11. def safely(&block)
  12. begin
  13. yield block
  14. rescue StandardError => e
  15. STDERR.puts "\nException #{e.message}:\n#{e.backtrace.join("\n")}\n\n"
  16. STDERR.puts "Terminating myself ..."
  17. STDERR.flush
  18. stop
  19. end
  20. end
  21. threads = []
  22. threads << Thread.new do
  23. safely do
  24. @stream = TwitterStream.new
  25. @stream.run
  26. puts "Twitter stream stopped ..."
  27. end
  28. end
  29. threads << Thread.new do
  30. safely do
  31. @scheduler = HuginnScheduler.new
  32. @scheduler.run!
  33. puts "Scheduler stopped ..."
  34. end
  35. end
  36. threads << Thread.new do
  37. safely do
  38. require 'delayed/command'
  39. @dj = Delayed::Worker.new
  40. @dj.start
  41. puts "Delayed job stopped ..."
  42. end
  43. end
  44. # We need to wait a bit to let delayed_job set it's traps so we can override them
  45. sleep 0.5
  46. trap('TERM') do
  47. stop
  48. end
  49. trap('INT') do
  50. stop
  51. end
  52. threads.collect { |t| t.join }