threaded.rb 1.1 KB

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