ssoroka (owner)

Revisions

gist: 118940 Download_button fork
public
Public Clone URL: git://gist.github.com/118940.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
######### bin/task_runner.rb ##########
 
# USAGE:
#
# ruby task_runner.rb run -- start the daemon and stay on top
# ruby task_runner.rb start -- start the daemon and stay on top
# ruby task_runner.rb stop stop all instances of the application
# ruby task_runner.rb restart stop all instances and restart them afterwards
 
require 'rubygems'
require 'daemons'
 
scheduler = File.join(File.dirname(__FILE__), '..', 'lib', 'scheduler.rb')
 
pid_dir = File.expand_path(File.join(File.dirname(__FILE__), %w(.. log)))
 
app_options = {
  :dir_mode => :normal,
  :dir => pid_dir,
  :multiple => false,
  :backtrace => true,
  :log_output => true
}
 
Daemons.run(scheduler, app_options)
 
######### lib/scheduler.rb ##########
 
# load the environment, just once. yay!
rails_root = File.expand_path(File.join(File.dirname(__FILE__), %w(.. ..)))
 
Dir.chdir(rails_root) do
  require File.join(rails_root, %w(config environment))
  puts "Loaded #{Rails.env} environment"
end
 
require 'eventmachine'
require 'rufus/scheduler'
 
# hijack puts() to include a timestamp
def puts(*args)
  printf("[#{Time.zone.now.to_s}] ")
  super(*args)
end
 
# load all custom tasks
tasks = []
Dir[File.join(File.dirname(__FILE__), %w(scheduled_tasks *.rb))].each{|f|
  begin
    require f
    filename = f.split('/').last.split('.').first
    puts "Loading task #{filename}..."
    tasks << filename.camelcase.constantize # path/newsfeed_task.rb => NewsfeedTask
  rescue
  end
}
 
puts "Starting Scheduler at #{Time.now.to_s(:date_with_time)}"
 
# tasks need to call ActiveRecord::Base.connection_pool.release_connection after running to
# release the connection back to the connection pool, Rails wont handle it for us here.
#
# Note: AR's ActiveRecord::Base.connection_pool.with_connection(&block) seems broken in
# that respect; it doesn't release the connection properly.
EventMachine::run {
  scheduler = Rufus::Scheduler::EmScheduler.start_new
 
  # This is where the magic happens. tasks in scheduled_tasks/*.rb are loaded up.
  tasks.each do |task|
    task.add_to scheduler
  end
 
  def scheduler.handle_exception(job, exception)
    puts "job #{job.job_id} caught exception '#{exception}'"
  end
}
 
######### lib/scheduled_tasks/expire_badges_task.rb ##########
 
module ExpireBadgesTask
  class <<self
    def add_to(scheduler)
      scheduler.every "24h", :first_at => Chronic.parse('midnight') do
        Badge.delete_expired!
        ActiveRecord::Base.connection_pool.release_connection
      end
    end
  end
end