continuity 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6c5ea26c39bd0c5f0525024d8686a7d6e9d9138b
4
+ data.tar.gz: 806194514cc94824a63c582231daa4c58294baca
5
+ SHA512:
6
+ metadata.gz: 667c3a275ec769b475ae40caaeaad976a495c7fedd703a236c12f52162fea72e219c51c766bf9ff4ee393e78c8b3c5e2aaeb9d1719125477ce38b9016f6089da
7
+ data.tar.gz: 19d273090408c49baf998fe5502d05f811cd1410abbd37d19c24a7b1149507bfdefe7e1a3e62eb19a88528ab22cdcec3383768edd457fdcdd6d3f422df703966
@@ -0,0 +1,5 @@
1
+ lib/**/*.rb
2
+ bin/*
3
+ -
4
+ features/**/*.feature
5
+ LICENSE.txt
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ source "http://rubygems.org"
2
+ # Add dependencies required to use your gem here.
3
+ # Example:
4
+ # gem "activesupport", ">= 2.3.5"
5
+ gem "redis"
6
+
7
+ # Add dependencies to develop your gem here.
8
+ # Include everything needed to run rake, tests, features, etc.
9
+ group :development do
10
+ gem "minitest", ">= 0"
11
+ gem "bundler", "~> 1.3.0"
12
+ gem "jeweler", "~> 1.8.7"
13
+ gem "simplecov", :require => false
14
+ end
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2010 Bob Potter
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,62 @@
1
+ = Continuity
2
+
3
+ NOTE: this has a decent amount of test coverage, but has yet to be tested in any kind of production environment. I hope to do some more real-worldish testing soon.
4
+
5
+ Allows you to share scheduling duties across any number of workers. Unlike other solutions (clockwork/rufus-scheduler) it doesn't introduce a single point of failure rely by relying on a single, always running scheduling process. Workers use Redis to coordinate scheduling duties. The scheduler will never miss a job, even if all workers are shut down for a period of time it will pick up from where it left off
6
+
7
+ Continuity only runs one job at a time, so your tasks should create jobs in Resque, DJ, etc and not actually do the heavy lifting themselves.
8
+
9
+ Redis could conceivably be replaced by any consistent datastore.
10
+
11
+ = Example
12
+
13
+ scheduler = Continuity::Scheduler.new_using_redis(redis_handle)
14
+
15
+ scheduler.every('10s') do
16
+ Resque.enqueue(PeriodicJob)
17
+ end
18
+
19
+ scheduler.cron('0 0 * * * *') do
20
+ Resque.enqueue(DailyJob)
21
+ end
22
+
23
+ scheduler.cron('0 * * * *') do
24
+ Resque.enqueue(DailyJob)
25
+ end
26
+
27
+ # main worker loop
28
+ loop do
29
+ do_job
30
+ scheduler.maybe_schedule
31
+ end
32
+
33
+ = Cron
34
+
35
+ * Supports a sixth field at the front for seconds.
36
+ * It doesn't support month/day names, use the numeral.
37
+ * In many cron implementations entries specifying the day of the month and day of the week (i.e. "0 0 11 1,5 * mon") have a special meaning, this is not supported.
38
+
39
+ = On Schedule Hook
40
+
41
+ scheduler.on_schedule do |range|
42
+ delayed_jobs = $redis.zrangebyscore(:delayed_jobs, range.first, range.last)
43
+ delayed_jobs.each do |job|
44
+ do_it(job)
45
+ end
46
+ end
47
+
48
+ == Contributing to continuity
49
+
50
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
51
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
52
+ * Fork the project
53
+ * Start a feature/bugfix branch
54
+ * Commit and push until you are happy with your contribution
55
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
56
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
57
+
58
+ == Copyright
59
+
60
+ Copyright (c) 2010 Bob Potter. See LICENSE.txt for
61
+ further details.
62
+
@@ -0,0 +1,46 @@
1
+ require 'rubygems'
2
+ require 'bundler'
3
+ begin
4
+ Bundler.setup(:default, :development)
5
+ rescue Bundler::BundlerError => e
6
+ $stderr.puts e.message
7
+ $stderr.puts "Run `bundle install` to install missing gems"
8
+ exit e.status_code
9
+ end
10
+ require 'rake'
11
+
12
+ require 'jeweler'
13
+ Jeweler::Tasks.new do |gem|
14
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
15
+ gem.name = "continuity"
16
+ gem.homepage = "http://github.com/bpot/continuity"
17
+ gem.license = "MIT"
18
+ gem.summary = %q{Allows you to distribute job scheduling across a number of processes}
19
+ gem.description = %q{Distributed scheduling of jobs}
20
+ gem.email = "bobby.potter@gmail.com"
21
+ gem.authors = ["Bob Potter"]
22
+ # Include your dependencies below. Runtime dependencies are required when using your gem,
23
+ # and development dependencies are only needed for development (ie running rake tasks, tests, etc)
24
+ # gem.add_runtime_dependency 'jabber4r', '> 0.1'
25
+ # gem.add_development_dependency 'rspec', '> 1.2.3'
26
+ end
27
+ Jeweler::RubygemsDotOrgTasks.new
28
+
29
+ require 'rake/testtask'
30
+ Rake::TestTask.new(:test) do |test|
31
+ test.libs << 'lib' << 'test'
32
+ test.pattern = 'test/**/test_*.rb'
33
+ test.verbose = true
34
+ end
35
+
36
+ task :default => :test
37
+
38
+ require 'rdoc/task'
39
+ Rake::RDocTask.new do |rdoc|
40
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
41
+
42
+ rdoc.rdoc_dir = 'rdoc'
43
+ rdoc.title = "continuity #{version}"
44
+ rdoc.rdoc_files.include('README*')
45
+ rdoc.rdoc_files.include('lib/**/*.rb')
46
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.1
@@ -0,0 +1,71 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "continuity"
8
+ s.version = "0.0.1"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Bob Potter"]
12
+ s.date = "2013-09-11"
13
+ s.description = "Distributed scheduling of jobs"
14
+ s.email = "bobby.potter@gmail.com"
15
+ s.extra_rdoc_files = [
16
+ "LICENSE.txt",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ "Gemfile",
22
+ "LICENSE.txt",
23
+ "README.rdoc",
24
+ "Rakefile",
25
+ "VERSION",
26
+ "continuity.gemspec",
27
+ "examples/worker.rb",
28
+ "lib/continuity.rb",
29
+ "lib/continuity/cron_entry.rb",
30
+ "lib/continuity/periodic_entry.rb",
31
+ "lib/continuity/redis_backend.rb",
32
+ "lib/continuity/scheduler.rb",
33
+ "test/helper.rb",
34
+ "test/redis.conf",
35
+ "test/test_cron_entry.rb",
36
+ "test/test_periodic_entry.rb",
37
+ "test/test_race_issues.rb",
38
+ "test/test_redis_backend.rb",
39
+ "test/test_scheduler.rb"
40
+ ]
41
+ s.homepage = "http://github.com/bpot/continuity"
42
+ s.licenses = ["MIT"]
43
+ s.require_paths = ["lib"]
44
+ s.rubygems_version = "2.0.2"
45
+ s.summary = "Allows you to distribute job scheduling across a number of processes"
46
+
47
+ if s.respond_to? :specification_version then
48
+ s.specification_version = 4
49
+
50
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
51
+ s.add_runtime_dependency(%q<redis>, [">= 0"])
52
+ s.add_development_dependency(%q<minitest>, [">= 0"])
53
+ s.add_development_dependency(%q<bundler>, ["~> 1.3.0"])
54
+ s.add_development_dependency(%q<jeweler>, ["~> 1.8.7"])
55
+ s.add_development_dependency(%q<simplecov>, [">= 0"])
56
+ else
57
+ s.add_dependency(%q<redis>, [">= 0"])
58
+ s.add_dependency(%q<minitest>, [">= 0"])
59
+ s.add_dependency(%q<bundler>, ["~> 1.3.0"])
60
+ s.add_dependency(%q<jeweler>, ["~> 1.8.7"])
61
+ s.add_dependency(%q<simplecov>, [">= 0"])
62
+ end
63
+ else
64
+ s.add_dependency(%q<redis>, [">= 0"])
65
+ s.add_dependency(%q<minitest>, [">= 0"])
66
+ s.add_dependency(%q<bundler>, ["~> 1.3.0"])
67
+ s.add_dependency(%q<jeweler>, ["~> 1.8.7"])
68
+ s.add_dependency(%q<simplecov>, [">= 0"])
69
+ end
70
+ end
71
+
@@ -0,0 +1,17 @@
1
+ require 'continuity'
2
+
3
+ redis = Redis.new(:port => 16379)
4
+ scheduler = Continuity::Scheduler.new_using_redis(redis)
5
+
6
+ scheduler.cron("*/10 * * * * *") do
7
+ print "10s schedulage on #{$$}\n"
8
+ end
9
+
10
+ scheduler.every("1m") do
11
+ print "1m schedulage on #{$$}\n"
12
+ end
13
+
14
+ loop do
15
+ sleep rand(5)
16
+ scheduler.run
17
+ end
@@ -0,0 +1,5 @@
1
+ require 'redis'
2
+ require 'continuity/redis_backend'
3
+ require 'continuity/cron_entry'
4
+ require 'continuity/periodic_entry'
5
+ require 'continuity/scheduler'
@@ -0,0 +1,91 @@
1
+ module Continuity
2
+ class CronFormatError < StandardError; end
3
+ class CronEntry
4
+ def initialize(entry)
5
+ @entry = entry
6
+
7
+ cron_parts = @entry.split(" ")
8
+ if cron_parts.size == 5
9
+ cron_parts.unshift("0")
10
+ elsif cron_parts.size != 6
11
+ raise CronFormatError, "Cron entry is invalid: #{@entry}"
12
+ end
13
+
14
+ seconds, minutes, hours, dates, months, dayofweek = *cron_parts
15
+
16
+ @seconds_bits = get_bits(seconds, (0..60))
17
+ @minutes_bits = get_bits(minutes, (0..60))
18
+ @hours_bits = get_bits(hours, (0..60))
19
+ @doms_bits = get_bits(dates, (1..31))
20
+ @months_bits = get_bits(months, (1..12))
21
+ @dows_bits = get_bits(dayofweek,(0..7))
22
+ end
23
+
24
+ def at?(time)
25
+ tst(@seconds_bits, time.sec) &&
26
+ tst(@minutes_bits, time.min) &&
27
+ tst(@hours_bits , time.hour) &&
28
+ tst(@doms_bits , time.mday) &&
29
+ tst(@months_bits , time.month) &&
30
+ tst(@dows_bits , time.wday)
31
+ end
32
+
33
+ private
34
+
35
+ def get_bits(s, valid_range)
36
+ bits = 0
37
+
38
+ s.split(",").each do |r|
39
+ interval, range = parse_range_and_interval(r, valid_range)
40
+
41
+ range.step(interval) do |n|
42
+ bits |= 1 << n
43
+ end
44
+ end
45
+
46
+ bits
47
+ end
48
+
49
+ def parse_range_and_interval(s, valid_range)
50
+ # extract interval (if exists)
51
+ if s.include?("/")
52
+ s, interval = s.split("/")
53
+ interval = cast_and_validate_integer(interval, valid_range)
54
+ else
55
+ interval = 1
56
+ end
57
+
58
+ # determine trigger range
59
+ if s == "*"
60
+ trigger_range = valid_range
61
+ elsif s.include?("-")
62
+ low, high = s.split("-")
63
+
64
+ low = cast_and_validate_integer(low, valid_range)
65
+ high = cast_and_validate_integer(high, valid_range)
66
+ trigger_range = (low..high)
67
+ else
68
+ s = cast_and_validate_integer(s, valid_range)
69
+ trigger_range = (s..s)
70
+ end
71
+
72
+ return interval, trigger_range
73
+ end
74
+
75
+ def tst(bits, n)
76
+ (bits & (1 << n)) > 0
77
+ end
78
+
79
+ def cast_and_validate_integer(i, valid_range)
80
+ if i.match(/\d+/)
81
+ i = i.to_i
82
+
83
+ if valid_range.include?(i)
84
+ return i
85
+ end
86
+ end
87
+
88
+ raise CronFormatError, "Cron entry is invalid: #{@entry} (#{i} outside of #{valid_range}"
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,22 @@
1
+ module Continuity
2
+ class PeriodicEntry
3
+ PERIODS = {
4
+ "s" => 1,
5
+ "m" => 60,
6
+ "h" => 3600,
7
+ "d" => 86400,
8
+ "w" => 86400*7
9
+ }
10
+
11
+ def initialize(s)
12
+ matches = s.match(/(\d+)([smhdw])/)
13
+ raise "Unable to parse period: #{s}" if matches.nil?
14
+
15
+ @period = matches[1].to_i * PERIODS[matches[2]]
16
+ end
17
+
18
+ def at?(time)
19
+ time.to_i % @period == 0
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,79 @@
1
+ module Continuity
2
+ class RedisBackend
3
+ LOCK_KEY = "continuity_lock"
4
+ LAST_SCHED_KEY = "continuity_scheduled_up_to"
5
+
6
+ def initialize(redis, frequency = 10, lock_timeout = 30)
7
+ @redis = redis
8
+ @lock_timeout = lock_timeout
9
+ @frequency = frequency
10
+ end
11
+
12
+ def lock_for_scheduling(now)
13
+ scheduled_up_to = @redis.get(LAST_SCHED_KEY).to_i
14
+
15
+ # bootstrap
16
+ if scheduled_up_to == 0
17
+ lock(now) do
18
+
19
+ # double check that someone else has bootstrapped
20
+ # since we fetched the key
21
+ scheduled_up_to = @redis.get(LAST_SCHED_KEY).to_i
22
+ if scheduled_up_to == 0
23
+ yield now - 1
24
+ @redis.set(LAST_SCHED_KEY, now)
25
+
26
+ return now
27
+ else
28
+ return scheduled_up_to
29
+ end
30
+ end
31
+
32
+ end
33
+
34
+ # this is tricky, we only want to attempt a lock
35
+ # if there is a possibility we can schedule things.
36
+ # BUT, once we attain a lock we need to make sure
37
+ # someone else hasn't already scheduled that period
38
+ if (now - scheduled_up_to) >= @frequency
39
+ lock(now) do
40
+ scheduled_up_to = @redis.get(LAST_SCHED_KEY).to_i
41
+ if (now - scheduled_up_to) >= @frequency
42
+ # good we should still schedule
43
+ yield scheduled_up_to
44
+ @redis.set(LAST_SCHED_KEY, now)
45
+ scheduled_up_to = now
46
+ end
47
+ end
48
+ end
49
+
50
+ scheduled_up_to
51
+ end
52
+
53
+ private
54
+ # http://code.google.com/p/redis/wiki/SetnxCommand
55
+ def lock(now)
56
+ lock_expiration = now + @lock_timeout + 1
57
+ res = @redis.setnx(LOCK_KEY, lock_expiration)
58
+
59
+ acquired_lock = false
60
+ if res
61
+ acquired_lock = true
62
+ yield
63
+ else
64
+ current_expiration = @redis.get(LOCK_KEY).to_i
65
+ if current_expiration < now
66
+ new_expiration = now + @lock_timeout + 1
67
+ if current_expiration == @redis.getset(LOCK_KEY, new_expiration).to_i
68
+ acquired_lock = true
69
+ yield
70
+ end
71
+ end
72
+ end
73
+ ensure
74
+ if acquired_lock
75
+ @redis.del(LOCK_KEY)
76
+ end
77
+ end
78
+ end
79
+ end