nulogy-resque-scheduler 1.10.15

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,78 @@
1
+ ## 1.9.6 (2010-10-08)
2
+
3
+ * Support for custom job classes (like resque-status) (mattetti)
4
+
5
+ ## 1.9.5 (2010-09-09)
6
+
7
+ * Updated scheduler rake task to allow for an alternate setup task
8
+ to avoid loading the entire stack. (chewbranca)
9
+ * Fixed sig issue on win32 (#25)
10
+
11
+ ## 1.9.4 (2010-07-29)
12
+
13
+ * Adding ability to remove jobs from delayed queue (joshsz)
14
+ * Fixing issue #23 (removing .present? reference)
15
+
16
+ ## 1.9.3 (2010-07-07)
17
+
18
+ * Bug fix (#19)
19
+
20
+ ## 1.9.2 (2010-06-16)
21
+
22
+ * Fixing issue with redis gem 2.0.1 and redis server 1.2.6 (dbackeus)
23
+
24
+ ## 1.9.1 (2010-06-04)
25
+
26
+ * Fixing issue with redis server 1.2.6 and redis gem 2.0.1
27
+
28
+ ## 1.9.0 (2010-06-04)
29
+
30
+ * Adding redis 2.0 support (bpo)
31
+
32
+ ## 1.8.2 (2010-06-04)
33
+
34
+ * Adding queue now functionality to delayed timestamps (daviddoan)
35
+
36
+ ## 1.8.1 (2010-05-19)
37
+
38
+ * Adding rails_env for scheduled jobs to support scoping jobs by
39
+ RAILS_ENV (gravis).
40
+ * Fixing ruby 1.8.6 compatibility issue.
41
+ * Adding gemspec for bundler support.
42
+
43
+ ## 1.8.0 (2010-04-14)
44
+
45
+ * Moving version to match corresponding resque version
46
+ * Sorting schedule on Scheduler tab
47
+ * Adding tests for resque-web (gravis)
48
+
49
+ ## 1.0.5 (2010-03-01)
50
+
51
+ * Fixed support for overriding queue from schedule config.
52
+ * Removed resque-web dependency on loading the job classes for "Queue Now",
53
+ provided "queue" is specified in the schedule.
54
+ * The queue is now stored with the job and arguments in the delayed queue so
55
+ there is no longer a need for the scheduler to load job classes to introspect
56
+ the queue.
57
+
58
+ ## 1.0.4 (2010-02-26)
59
+
60
+ * Added support for specifying the queue to put the job onto. This allows for
61
+ you to have one job that can go onto multiple queues and be able to schedule
62
+ jobs without having to load the job classes.
63
+
64
+ ## 1.0.3 (2010-02-11)
65
+
66
+ * Added support for scheduled jobs with empty crons. This is helpful to have
67
+ jobs that you don't want on a schedule, but do want to be able to queue by
68
+ clicking a button.
69
+
70
+ ## 1.0.2 (2010-02-?)
71
+
72
+ * Change Delayed Job tab to display job details if only 1 job exists
73
+ for a given timestamp
74
+
75
+ ## 1.0.1 (2010-01-?)
76
+
77
+ * Bugfix: delayed jobs close together resulted in a 5 second sleep
78
+
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2010 Ben VandenBos
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.
21
+
@@ -0,0 +1,275 @@
1
+ resque-scheduler
2
+ ===============
3
+
4
+ Resque-scheduler is an extension to [Resque](http://github.com/defunkt/resque)
5
+ that adds support for queueing items in the future.
6
+
7
+ Requires redis >=1.1.
8
+
9
+
10
+ Job scheduling is supported in two different way:
11
+
12
+ ### Recurring (scheduled)
13
+
14
+ Recurring (or scheduled) jobs are logically no different than a standard cron
15
+ job. They are jobs that run based on a fixed schedule which is set at startup.
16
+
17
+ The schedule is a list of Resque worker classes with arguments and a
18
+ schedule frequency (in crontab syntax). The schedule is just a hash, but
19
+ is most likely stored in a YAML like so:
20
+
21
+ queue_documents_for_indexing:
22
+ cron: "0 0 * * *"
23
+ class: QueueDocuments
24
+ args:
25
+ description: "This job queues all content for indexing in solr"
26
+
27
+ clear_leaderboards_contributors:
28
+ cron: "30 6 * * 1"
29
+ class: ClearLeaderboards
30
+ args: contributors
31
+ description: "This job resets the weekly leaderboard for contributions"
32
+
33
+ A queue option can also be specified. When job will go onto the specified queue
34
+ if it is available (Even if @queue is specified in the job class). When the
35
+ queue is given it is not necessary for the scheduler to load the class.
36
+
37
+ clear_leaderboards_moderator:
38
+ cron: "30 6 * * 1"
39
+ class: ClearLeaderboards
40
+ queue: scoring
41
+ args: moderators
42
+ description: "This job resets the weekly leaderboard for moderators"
43
+
44
+ And then set the schedule wherever you configure Resque, like so:
45
+
46
+ require 'resque_scheduler'
47
+ Resque.schedule = YAML.load_file(File.join(File.dirname(__FILE__), '../resque_schedule.yml'))
48
+
49
+ Keep in mind, scheduled jobs behave like crons: if your scheduler process (more
50
+ on that later) is not running when a particular job is supposed to be queued,
51
+ it will NOT be ran later when the scheduler process is started back up. In that
52
+ sense, you can sort of think of the scheduler process as crond. Delayed jobs,
53
+ however, are different.
54
+
55
+ A big shout out to [rufus-scheduler](http://github.com/jmettraux/rufus-scheduler)
56
+ for handling the heavy lifting of the actual scheduling engine.
57
+
58
+ ### Delayed jobs
59
+
60
+ Delayed jobs are one-off jobs that you want to be put into a queue at some point
61
+ in the future. The classic example is sending email:
62
+
63
+ Resque.enqueue_at(5.days.from_now, SendFollowUpEmail, :user_id => current_user.id)
64
+
65
+ This will store the job for 5 days in the resque delayed queue at which time the
66
+ scheduler process will pull it from the delayed queue and put it in the
67
+ appropriate work queue for the given job and it will be processed as soon as
68
+ a worker is available.
69
+
70
+ NOTE: The job does not fire **exactly** at the time supplied. Rather, once that
71
+ time is in the past, the job moves from the delayed queue to the actual resque
72
+ work queue and will be completed as workers as free to process it.
73
+
74
+ Also supported is `Resque.enqueue_in` which takes an amount of time in seconds
75
+ in which to queue the job.
76
+
77
+ The delayed queue is stored in redis and is persisted in the same way the
78
+ standard resque jobs are persisted (redis writing to disk). Delayed jobs differ
79
+ from scheduled jobs in that if your scheduler process is down or workers are
80
+ down when a particular job is supposed to be queue, they will simply "catch up"
81
+ once they are started again. Jobs are guaranteed to run (provided they make it
82
+ into the delayed queue) after their given queue_at time has passed.
83
+
84
+ One other thing to note is that insertion into the delayed queue is O(log(n))
85
+ since the jobs are stored in a redis sorted set (zset). I can't imagine this
86
+ being an issue for someone since redis is stupidly fast even at log(n), but full
87
+ disclosure is always best.
88
+
89
+ *Removing Delayed jobs*
90
+
91
+ If you have the need to cancel a delayed job, you can do so thusly:
92
+
93
+ # after you've enqueued a job like:
94
+ Resque.enqueue_at(5.days.from_now, SendFollowUpEmail, :user_id => current_user.id)
95
+ # remove the job with exactly the same parameters:
96
+ Resque.remove_delayed(SendFollowUpEmail, :user_id => current_user.id)
97
+
98
+ ### Schedule jobs per environment
99
+
100
+ Resque-Scheduler allows to create schedule jobs for specific envs. The arg
101
+ `rails_env` (optional) can be used to determine which envs are concerned by the
102
+ job:
103
+
104
+ create_fake_leaderboards:
105
+ cron: "30 6 * * 1"
106
+ class: CreateFakeLeaderboards
107
+ queue: scoring
108
+ args:
109
+ rails_env: demo
110
+ description: "This job will auto-create leaderboards for our online demo"
111
+
112
+ The scheduled job create_fake_leaderboards will be created only if the
113
+ environment variable `RAILS_ENV` is set to demo:
114
+
115
+ $ RAILS_ENV=demo rake resque:scheduler
116
+
117
+ NOTE: If you have added the 2 lines bellow to your Rails Rakefile
118
+ (ie: lib/tasks/resque-scheduler.rake), the rails env is loaded automatically
119
+ and you don't have to specify RAILS_ENV if the var is correctly set in
120
+ environment.rb
121
+
122
+ Alternatively, you can use your resque initializer to avoid loading the entire
123
+ rails stack.
124
+
125
+ $ rake resque:scheduler INITIALIZER_PATH=config/initializers/resque.rb
126
+
127
+
128
+ Multiple envs are allowed, separated by commas:
129
+
130
+ create_fake_leaderboards:
131
+ cron: "30 6 * * 1"
132
+ class: CreateFakeLeaderboards
133
+ queue: scoring
134
+ args:
135
+ rails_env: demo, staging, production
136
+ description: "This job will auto-create leaderboards"
137
+
138
+ NOTE: If you specify the `rails_env` arg without setting RAILS_ENV as an
139
+ environment variable, the job won't be loaded.
140
+
141
+ ### Dynamic Schedules
142
+
143
+ If needed you can also have schedules that are dynamically defined and updated inside of your application. This can be completed by loading the schedule initially wherever you configure Resque and setting `Resque::Scheduler.dynamic` to `true`. Then subsequently updating the "`schedules`" key in redis, namespaced to the Resque namespace. The "`schedules`" key is expected to be a redis hash data type, where the key is the name of the schedule and the value is a JSON encoded hash of the schedule configuration.
144
+
145
+ When the scheduler loops it will look for differences between the existing schedule and the current schedule in redis. If there are differences it will make the necessary changes to the running schedule.
146
+
147
+ To force the scheduler to reload the schedule you just send it the `USR2` signal.
148
+
149
+ Convenience methods are provided to add/update, delete, and retrieve individual schedule items from the `schedules` in redis:
150
+
151
+ * `Resque.set_schedule(name, config)`
152
+ * `Resque.get_schedule(name)`
153
+ * `Resque.remove_schedule(name)`
154
+
155
+ For example:
156
+
157
+ Resque.set_schedule("create_fake_leaderboards", {
158
+ :cron => "30 6 * * 1",
159
+ :class => "CreateFakeLeaderboards",
160
+ :queue => scoring
161
+ })
162
+
163
+ ### Support for customized Job classes
164
+
165
+ Some Resque extensions like [resque-status](http://github.com/quirkey/resque-status) use custom job classes with a slightly different API signature.
166
+ Resque-scheduler isn't trying to support all existing and future custom job classes, instead it supports a schedule flag so you can extend your custom class
167
+ and make it support scheduled job.
168
+
169
+ Let's pretend we have a JobWithStatus class called FakeLeaderboard
170
+
171
+ class FakeLeaderboard < Resque::JobWithStatus
172
+ def perfom
173
+ # do something and keep track of the status
174
+ end
175
+ end
176
+
177
+ create_fake_leaderboards:
178
+ cron: "30 6 * * 1"
179
+ queue: scoring
180
+ custom_job_class: FakeLeaderboard
181
+ args:
182
+ rails_env: demo
183
+ description: "This job will auto-create leaderboards for our online demo and the status will update as the worker makes progress"
184
+
185
+ If your extension doesn't support scheduled job, you would need to extend the custom job class to support the #scheduled method:
186
+
187
+ module Resque
188
+ class JobWithStatus
189
+ # Wrapper API to forward a Resque::Job creation API call into a JobWithStatus call.
190
+ def self.scheduled(queue, klass, *args)
191
+ create(args)
192
+ end
193
+ end
194
+ end
195
+
196
+
197
+ Resque-web additions
198
+ --------------------
199
+
200
+ Resque-scheduler also adds to tabs to the resque-web UI. One is for viewing
201
+ (and manually queueing) the schedule and one is for viewing pending jobs in
202
+ the delayed queue.
203
+
204
+ The Schedule tab:
205
+
206
+ ![The Schedule Tab](http://img.skitch.com/20100111-km2f5gmtpbq23enpujbruj6mgk.png)
207
+
208
+ The Delayed tab:
209
+
210
+ ![The Delayed Tab](http://img.skitch.com/20100111-ne4fcqtc5emkcuwc5qtais2kwx.jpg)
211
+
212
+ Get get these to show up you need to pass a file to `resque-web` to tell it to
213
+ include the `resque-scheduler` plugin. You probably already have a file somewhere
214
+ where you configure `resque`. It probably looks something like this:
215
+
216
+ require 'resque' # include resque so we can configure it
217
+ Resque.redis = "redis_server:6379" # tell Resque where redis lives
218
+
219
+ Now, you want to add the following:
220
+
221
+ require 'resque_scheduler' # include the resque_scheduler (this makes the tabs show up)
222
+
223
+ And if you have a schedule you want to set, add this:
224
+
225
+ Resque.schedule = YAML.load_file(File.join(RAILS_ROOT, 'config/resque_schedule.yml')) # load the schedule
226
+
227
+ Now make sure you're passing that file to resque-web like so:
228
+
229
+ resque-web ~/yourapp/config/resque_config.rb
230
+
231
+ That should make the scheduler tabs show up in `resque-web`.
232
+
233
+
234
+
235
+ Installation and the Scheduler process
236
+ --------------------------------------
237
+
238
+ To install:
239
+
240
+ gem install resque-scheduler
241
+
242
+ You'll need to add this to your rakefile:
243
+
244
+ require 'resque_scheduler/tasks'
245
+ task "resque:setup" => :environment
246
+
247
+ The scheduler process is just a rake task which is responsible for both queueing
248
+ items from the schedule and polling the delayed queue for items ready to be
249
+ pushed on to the work queues. For obvious reasons, this process never exits.
250
+
251
+ $ rake resque:scheduler
252
+
253
+ Supported environment variables are `VERBOSE` and `MUTE`. If either is set to
254
+ any nonempty value, they will take effect. `VERBOSE` simply dumps more output
255
+ to stdout. `MUTE` does the opposite and silences all output. `MUTE` supercedes
256
+ `VERBOSE`.
257
+
258
+ NOTE: You DO NOT want to run >1 instance of the scheduler. Doing so will result
259
+ in the same job being queued more than once. You only need one instnace of the
260
+ scheduler running per resque instance (regardless of number of machines).
261
+
262
+
263
+ Plagurism alert
264
+ ---------------
265
+
266
+ This was intended to be an extension to resque and so resulted in a lot of the
267
+ code looking very similar to resque, particularly in resque-web and the views. I
268
+ wanted it to be similar enough that someone familiar with resque could easily
269
+ work on resque-scheduler.
270
+
271
+
272
+ Contributing
273
+ ------------
274
+
275
+ For bugs or suggestions, please just open an issue in github.
@@ -0,0 +1,49 @@
1
+ load File.expand_path('tasks/resque_scheduler.rake')
2
+
3
+ $LOAD_PATH.unshift 'lib'
4
+
5
+ task :default => :test
6
+
7
+ desc "Run tests"
8
+ task :test do
9
+ Dir['test/*_test.rb'].each do |f|
10
+ require File.expand_path(f)
11
+ end
12
+ end
13
+
14
+
15
+ desc "Build a gem"
16
+ task :gem => [ :test, :gemspec, :build ]
17
+
18
+ begin
19
+ begin
20
+ require 'jeweler'
21
+ rescue LoadError
22
+ puts "Jeweler not available. Install it with: "
23
+ puts "gem install jeweler"
24
+ end
25
+
26
+ require 'resque_scheduler/version'
27
+
28
+ Jeweler::Tasks.new do |gemspec|
29
+ gemspec.name = "nulogy-resque-scheduler"
30
+ gemspec.summary = "Light weight job scheduling on top of Resque"
31
+ gemspec.description = %{Light weight job scheduling on top of Resque.
32
+ Adds methods enqueue_at/enqueue_in to schedule jobs in the future.
33
+ Also supports queueing jobs on a fixed, cron-like schedule.}
34
+ gemspec.email = "engineering@nulogy.com"
35
+ gemspec.homepage = "http://github.com/nulogy/resque-scheduler"
36
+ gemspec.authors = ["Ben VandenBos", "Brian Landau", "Sean Kirby", "Tanzeeb Khalili", "Justin Fitzsimmons"]
37
+ gemspec.version = ResqueScheduler::Version
38
+
39
+ gemspec.add_dependency "redis", ">= 2.0.1"
40
+ gemspec.add_dependency "resque", ">= 1.8.0"
41
+ gemspec.add_dependency "tanzeeb-rufus-scheduler"
42
+ gemspec.add_dependency "airbrake"
43
+ gemspec.add_development_dependency "jeweler"
44
+ gemspec.add_development_dependency "mocha"
45
+ gemspec.add_development_dependency "rack-test"
46
+ end
47
+
48
+ Jeweler::GemcutterTasks.new
49
+ end
@@ -0,0 +1,256 @@
1
+ require 'rufus/scheduler'
2
+ require 'airbrake'
3
+ require 'thwait'
4
+
5
+ module Resque
6
+
7
+ class Scheduler
8
+
9
+ extend Resque::Helpers
10
+
11
+ class << self
12
+
13
+ # If true, logs more stuff...
14
+ attr_accessor :verbose
15
+
16
+ # If set, produces no output
17
+ attr_accessor :mute
18
+
19
+ # If set, will try to update the schulde in the loop
20
+ attr_accessor :dynamic
21
+
22
+ # If set, will tell rufus to use the airbrake exception handler
23
+ attr_accessor :airbrake
24
+
25
+ # the Rufus::Scheduler jobs that are scheduled
26
+ def scheduled_jobs
27
+ @@scheduled_jobs
28
+ end
29
+
30
+ # Schedule all jobs and continually look for delayed jobs (never returns)
31
+ def run
32
+ $0 = "resque-scheduler: Starting"
33
+ # trap signals
34
+ register_signal_handlers
35
+
36
+ # Load the schedule into rufus
37
+ procline "Loading Schedule"
38
+ load_schedule!
39
+
40
+ # Now start the scheduling part of the loop.
41
+ loop do
42
+ handle_delayed_items
43
+ update_schedule if dynamic
44
+ poll_sleep
45
+ end
46
+
47
+ # never gets here.
48
+ end
49
+
50
+ # For all signals, set the shutdown flag and wait for current
51
+ # poll/enqueing to finish (should be almost istant). In the
52
+ # case of sleeping, exit immediately.
53
+ def register_signal_handlers
54
+ trap("TERM") { shutdown }
55
+ trap("INT") { shutdown }
56
+
57
+ begin
58
+ trap('QUIT') { shutdown }
59
+ trap('USR1') { kill_child }
60
+ trap('USR2') { reload_schedule! }
61
+ rescue ArgumentError
62
+ warn "Signals QUIT and USR1 and USR2 not supported."
63
+ end
64
+ end
65
+
66
+ # Pulls the schedule from Resque.schedule and loads it into the
67
+ # rufus scheduler instance
68
+ def load_schedule!
69
+ log! "Schedule empty! Set Resque.schedule" if Resque.schedule.empty?
70
+
71
+ @@scheduled_jobs = {}
72
+
73
+ Resque.schedule.each do |name, config|
74
+ load_schedule_job(name, config)
75
+ end
76
+ Resque.redis.del(:schedules_changed)
77
+ procline "Schedules Loaded"
78
+ end
79
+
80
+ # Loads a job schedule into the Rufus::Scheduler and stores it in @@scheduled_jobs
81
+ def load_schedule_job(name, config)
82
+ # If rails_env is set in the config, enforce ENV['RAILS_ENV'] as
83
+ # required for the jobs to be scheduled. If rails_env is missing, the
84
+ # job should be scheduled regardless of what ENV['RAILS_ENV'] is set
85
+ # to.
86
+ if config['rails_env'].nil? || rails_env_matches?(config)
87
+ log! "Scheduling #{name} "
88
+ interval_defined = false
89
+ interval_types = %w{cron every}
90
+ interval_types.each do |interval_type|
91
+ if !config[interval_type].nil? && config[interval_type].length > 0
92
+ begin
93
+ @@scheduled_jobs[name] = rufus_scheduler.send(interval_type, config[interval_type]) do
94
+ log! "queueing #{config['class']} (#{name})"
95
+ enqueue_from_config(config)
96
+ end
97
+ rescue Exception => e
98
+ log! "#{e.class.name}: #{e.message}"
99
+ end
100
+ interval_defined = true
101
+ break
102
+ end
103
+ end
104
+ unless interval_defined
105
+ log! "no #{interval_types.join(' / ')} found for #{config['class']} (#{name}) - skipping"
106
+ end
107
+ end
108
+ end
109
+
110
+ # Returns true if the given schedule config hash matches the current
111
+ # ENV['RAILS_ENV']
112
+ def rails_env_matches?(config)
113
+ config['rails_env'] && ENV['RAILS_ENV'] && config['rails_env'].gsub(/\s/,'').split(',').include?(ENV['RAILS_ENV'])
114
+ end
115
+
116
+ # Handles queueing delayed items
117
+ def handle_delayed_items(at_time = nil)
118
+ if timestamp = Resque.next_delayed_timestamp(at_time)
119
+ procline "Processing Delayed Items"
120
+ while !timestamp.nil?
121
+ enqueue_delayed_items_for_timestamp(timestamp)
122
+ timestamp = Resque.next_delayed_timestamp(at_time)
123
+ end
124
+ end
125
+ end
126
+
127
+ # Enqueues all delayed jobs for a timestamp
128
+ def enqueue_delayed_items_for_timestamp(timestamp)
129
+ item = nil
130
+ begin
131
+ handle_shutdown do
132
+ if item = Resque.next_item_for_timestamp(timestamp)
133
+ log "queuing #{item['class']} [delayed]"
134
+ klass = constantize(item['class'])
135
+ queue = item['queue'] || Resque.queue_from_class(klass)
136
+ # Support custom job classes like job with status
137
+ if (job_klass = item['custom_job_class']) && (job_klass != 'Resque::Job')
138
+ # custom job classes not supporting the same API calls must implement the #schedule method
139
+ constantize(job_klass).scheduled(queue, item['class'], *item['args'])
140
+ else
141
+ Resque.enqueue_to(queue, klass, *item['args'])
142
+ #Resque::Job.create(queue, klass, *item['args'])
143
+ end
144
+ end
145
+ end
146
+ # continue processing until there are no more ready items in this timestamp
147
+ end while !item.nil?
148
+ end
149
+
150
+ def handle_shutdown
151
+ exit if @shutdown
152
+ yield
153
+ exit if @shutdown
154
+ end
155
+
156
+ # Enqueues a job based on a config hash
157
+ def enqueue_from_config(config)
158
+ args = config['args'] || config[:args]
159
+ klass_name = config['class'] || config[:class]
160
+ klass = constantize(klass_name)
161
+ params = args.nil? ? [] : Array(args)
162
+ queue = config['queue'] || config[:queue] || Resque.queue_from_class(klass)
163
+ # Support custom job classes like job with status
164
+ if (job_klass = config['custom_job_class']) && (job_klass != 'Resque::Job')
165
+ # custom job classes not supporting the same API calls must implement the #schedule method
166
+ constantize(job_klass).scheduled(queue, klass_name, *params)
167
+ else
168
+ Resque.enqueue_to(queue, klass, *params)
169
+ end
170
+ end
171
+
172
+ def rufus_scheduler
173
+ @rufus_scheduler ||= Rufus::Scheduler.start_new
174
+ if self.airbrake
175
+ def @rufus_scheduler.handle_exception(job, exception)
176
+ puts "Exception caught, notifying Airbrake"
177
+ id = Airbrake.notify(exception)
178
+ puts "Airbrake id: #{id}"
179
+ end
180
+ end
181
+ @rufus_scheduler
182
+ end
183
+
184
+ # Stops old rufus scheduler and creates a new one. Returns the new
185
+ # rufus scheduler
186
+ def clear_schedule!
187
+ rufus_scheduler.stop
188
+ @rufus_scheduler = nil
189
+ @@scheduled_jobs = {}
190
+ rufus_scheduler
191
+ end
192
+
193
+ def reload_schedule!
194
+ procline "Reloading Schedule"
195
+ clear_schedule!
196
+ Resque.reload_schedule!
197
+ load_schedule!
198
+ end
199
+
200
+ def update_schedule
201
+ if Resque.redis.scard(:schedules_changed) > 0
202
+ procline "Updating schedule"
203
+ Resque.reload_schedule!
204
+ while schedule_name = Resque.redis.spop(:schedules_changed)
205
+ if Resque.schedule.keys.include?(schedule_name)
206
+ unschedule_job(schedule_name)
207
+ load_schedule_job(schedule_name, Resque.schedule[schedule_name])
208
+ else
209
+ unschedule_job(schedule_name)
210
+ end
211
+ end
212
+ end
213
+ procline "Schedules Loaded"
214
+ end
215
+
216
+ def unschedule_job(name)
217
+ if scheduled_jobs[name]
218
+ log "Removing schedule #{name}"
219
+ scheduled_jobs[name].unschedule
220
+ @@scheduled_jobs.delete(name)
221
+ end
222
+ end
223
+
224
+ # Sleeps and returns true
225
+ def poll_sleep
226
+ @sleeping = true
227
+ handle_shutdown { sleep 5 }
228
+ @sleeping = false
229
+ true
230
+ end
231
+
232
+ # Sets the shutdown flag, exits if sleeping
233
+ def shutdown
234
+ @shutdown = true
235
+ exit if @sleeping
236
+ end
237
+
238
+ def log!(msg)
239
+ puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} #{msg}" unless mute
240
+ end
241
+
242
+ def log(msg)
243
+ # add "verbose" logic later
244
+ log!(msg) if verbose
245
+ end
246
+
247
+ def procline(string)
248
+ $0 = "resque-scheduler-#{ResqueScheduler::Version}: #{string}"
249
+ log! $0
250
+ end
251
+
252
+ end
253
+
254
+ end
255
+
256
+ end