trabajo-afectivo/app/models/scheduler.rb

61 lines
1.5 KiB
Ruby
Raw Normal View History

2013-03-05 08:38:58 +00:00
class Scheduler < ApplicationModel
2013-05-07 20:45:00 +00:00
def self.run( worker, worker_count )
2013-03-05 08:38:58 +00:00
Thread.abort_on_exception = true
2013-05-07 20:45:00 +00:00
jobs_started = {}
2013-03-05 08:38:58 +00:00
while true
2013-05-07 20:45:00 +00:00
puts "Scheduler running (worker #{worker} of #{worker_count})..."
# read/load jobs and check if it is alredy started
jobs = Scheduler.where( 'active = ? AND prio = ?', true, worker )
jobs.each {|job|
next if jobs_started[ job.id ]
jobs_started[ job.id ] = true
self.start_job( job, worker, worker_count )
}
sleep 45
2013-03-05 08:38:58 +00:00
end
end
2013-05-07 20:45:00 +00:00
def self.start_job( job, worker, worker_count )
2013-03-05 08:38:58 +00:00
puts "started job thread for '#{job.name}' (#{job.method})..."
2013-05-07 20:45:00 +00:00
sleep 4
2013-03-05 08:38:58 +00:00
Thread.new {
if job.period
while true
2013-05-07 20:45:00 +00:00
self._start_job( job, worker, worker_count )
2013-03-05 08:38:58 +00:00
job = Scheduler.where( :id => job.id ).first
2013-05-07 20:45:00 +00:00
# exit is job got deleted
2013-03-05 08:38:58 +00:00
break if !job
2013-05-07 20:45:00 +00:00
# exit if job is not active anymore
2013-03-05 08:38:58 +00:00
break if !job.active
2013-05-07 20:45:00 +00:00
# exit if there is no loop period defined
2013-03-05 08:38:58 +00:00
break if !job.period
2013-05-07 20:45:00 +00:00
# wait until next run
2013-03-05 08:38:58 +00:00
sleep job.period
end
else
2013-05-07 20:45:00 +00:00
self._start_job( job, worker, worker_count )
2013-03-05 08:38:58 +00:00
end
# raise "Exception from thread"
job.pid = ''
job.save
puts " ...stopped thread for '#{job.method}'"
}
end
2013-05-07 20:45:00 +00:00
def self._start_job( job, worker, worker_count )
2013-05-07 21:34:58 +00:00
puts "execute #{job.method} (worker #{worker} of #{worker_count})..."
2013-03-05 08:38:58 +00:00
job.last_run = Time.now
job.pid = Thread.current.object_id
job.save
2013-05-07 20:45:00 +00:00
eval job.method()
2013-03-05 08:38:58 +00:00
end
end