Created
July 23, 2012 21:46
-
-
Save threez/3166431 to your computer and use it in GitHub Desktop.
Disibuted CRON?!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Job, Desc, Interval, Tick, updated_at | |
class Job | |
attr_reader :name | |
attr_accessor :task, :working | |
def initialize(name, interval, offset) | |
@name = name | |
@interval = interval | |
@offset = offset | |
@executed_at = 0 | |
@alive = false | |
end | |
def check(at = Time.now) | |
frame = (at.to_i % @interval) - @offset | |
# check how often the interval was checked, what if | |
# the job finished in a time longer than the interval? | |
if (frame >= 0) && (frame < @interval * 0.20) && | |
(at.to_i - @executed_at) >= @interval | |
if @alive | |
@working.call(at.to_i - @executed_at) if @working | |
@alive = false if @alive && rand > 0.7 | |
else | |
@task.call(at.to_i - @executed_at) if @task | |
@executed_at = at.to_i | |
@alive = true | |
end | |
end | |
end | |
end | |
# UPDATE jobs SET updated_t = Time.now, tick = tick + 1, worker = 1 | |
# WHERE Time.now - updated_at >= 1 AND id = X | |
# SELECT worker, active FROM jobs WHERE id = X | |
jobs = [ | |
Job.new("Clean dishes every 5s", 5, 0), | |
Job.new("Clean kitchen", | |
24 * 60 * 60, | |
8 * 60 * 60 - 2 * 60 * 60 + # 2h (GMT + Summertime) | |
23 * 60) | |
] | |
jobs.each_with_index do |job, i| | |
job.task = lambda { |after| | |
puts "execute #{job.name.inspect} by #{i + 1}. thread after #{after}" | |
} | |
job.working = lambda { |since| | |
puts "still processing since #{since}" | |
} | |
end | |
workers = [] | |
5.times do |i| | |
workers << Thread.new do | |
sleep i * rand | |
loop do | |
jobs.each do |job| | |
job.check | |
end | |
sleep 5 * rand | |
end | |
end | |
end | |
workers.each(&:join) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment