Fix for GitHub issue 10

69 views
Skip to first unread message

Shogun

unread,
Mar 4, 2011, 2:36:34 AM3/4/11
to Rufus Ruby
Hi!
I actually found a nice way (which could, of course, be improved) to
handle GitHub issue 10 (https://github.com/jmettraux/rufus-scheduler/
issues/10/) with Passenger.
Basically, i use Passenger events and a lock (PID) file to make sure
than at any time at least a Rufus::Scheduler is active.
For my servers (tested both on OSX and Linux) it works either with
passenger_pool_idle_time set to 0 and > 0. Probably the only
requirement is passenger_min_instances >= 1.

The code follows, hope it helps. Basically you should only redefine
the execute_scheduler function basing on your needs.

---- CODE BEGIN ---
# encoding: utf-8

def execute_scheduler
# Create your scheduler here
scheduler = Rufus::Scheduler.start_new
logger = Logger.new(Rails.root.to_s + "/log/scheduler.log")

# Test job
scheduler.every("10m") do
logger.info "Log"
end
end

# Create the main logger and set some useful variables.
main_logger = Logger.new(Rails.root.to_s + "/log/scheduler.log")
pid_file = (Rails.root.to_s + "/tmp/pids/scheduler").to_s
File.delete(pid_file) if FileTest.exists?(pid_file)

if defined?(PhusionPassenger) then
# Passenger is starting a new process
PhusionPassenger.on_event(:starting_worker_process) do |forked|
# If we are forked and there's no pid file (that is no lock)
if forked && !FileTest.exists?(pid_file) then
main_logger.debug "SCHEDULER START ON PROCESS #{$$}"
# Write the current PID on the file
File.open(pid_file, "w") {
|f| f.write($$)
}

# Execute the scheduler
execute_scheduler
end
end
# Passenger is shutting down a process.
PhusionPassenger.on_event(:stopping_worker_process) do
# If a pid file exists and the process which
# is being shutted down is the same which holds the lock
# (in other words, the process which is executing the
scheduler)
# we remove the lock.
if FileTest.exists?(pid_file) then
if File.open(pid_file, "r") {|f| pid = f.read.to_i} == $$
then
main_logger.debug "SCHEDULER STOP ON PROCESS #{$$}"
File.delete(pid_file)
end
end
end
else # Only execute one scheduler
execute_scheduler
end

main_logger.info "SCHEDULER START"
--- CODE END ---

Best regards!
Shogun

Stephen Lottermoser

unread,
Apr 30, 2012, 8:07:04 PM4/30/12
to rufus...@googlegroups.com
Awesome! Did you just stick this in an initializers file?

Stephen Lottermoser

unread,
May 1, 2012, 1:25:03 AM5/1/12
to rufus...@googlegroups.com
Shogun, thank you! This worked like a charm :)
Reply all
Reply to author
Forward
0 new messages