Class: Sidekiq::Cron::Job

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq/cron/job.rb

Constant Summary collapse

REMEMBER_THRESHOLD =

How long we would like to store informations about previous enqueues.

24 * 60 * 60
LAST_ENQUEUE_TIME_FORMAT =

Time format for enqueued jobs.

'%Y-%m-%d %H:%M:%S %z'
REDIS_EXISTS_METHOD =

Use the exists? method if we’re on a newer version of Redis.

Gem::Version.new(Sidekiq::VERSION) >= Gem::Version.new("7.0.0") || Gem.loaded_specs['redis'].version < Gem::Version.new('4.2') ? :exists : :exists?

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_args = {}) ⇒ Job

Returns a new instance of Job.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/sidekiq/cron/job.rb', line 267

def initialize input_args = {}
  args = Hash[input_args.map{ |k, v| [k.to_s, v] }]
  @fetch_missing_args = args.delete('fetch_missing_args')
  @fetch_missing_args = true if @fetch_missing_args.nil?

  @name = args["name"]
  @cron = args["cron"]
  @description = args["description"] if args["description"]

  # Get class from klass or class.
  @klass = args["klass"] || args["class"]

  # Set status of job.
  @status = args['status'] || status_from_redis

  # Set last enqueue time - from args or from existing job.
  if args['last_enqueue_time'] && !args['last_enqueue_time'].empty?
    @last_enqueue_time = parse_enqueue_time(args['last_enqueue_time'])
  else
    @last_enqueue_time = last_enqueue_time_from_redis
  end

  # Get right arguments for job.
  @symbolize_args = args["symbolize_args"] == true || ("#{args["symbolize_args"]}" =~ (/^(true|t|yes|y|1)$/i)) == 0 || false
  @args = args["args"].nil? ? [] : parse_args( args["args"] )

  @date_as_argument = args["date_as_argument"] == true || ("#{args["date_as_argument"]}" =~ (/^(true|t|yes|y|1)$/i)) == 0 || false

  @active_job = args["active_job"] == true || ("#{args["active_job"]}" =~ (/^(true|t|yes|y|1)$/i)) == 0 || false
  @active_job_queue_name_prefix = args["queue_name_prefix"]
  @active_job_queue_name_delimiter = args["queue_name_delimiter"]

  if args["message"]
    @message = args["message"]
    message_data = Sidekiq.load_json(@message) || {}
    @queue = message_data['queue'] || "default"
  elsif @klass
    message_data = {
      "class" => @klass.to_s,
      "args"  => @args,
    }

    # Get right data for message,
    # only if message wasn't specified before.
    klass_data = case @klass
      when Class
        @klass.get_sidekiq_options
      when String
        begin
          Sidekiq::Cron::Support.constantize(@klass).get_sidekiq_options
        rescue Exception => e
          # Unknown class
          {"queue"=>"default"}
        end
    end

    message_data = klass_data.merge(message_data)

    # Override queue if setted in config,
    # only if message is hash - can be string (dumped JSON).
    if args['queue']
      @queue = message_data['queue'] = args['queue']
    else
      @queue = message_data['queue'] || "default"
    end

    @message = message_data
  end

  @queue_name_with_prefix = queue_name_with_prefix
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def args
  @args
end

#cronObject

Returns the value of attribute cron.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def cron
  @cron
end

#descriptionObject

Returns the value of attribute description.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def description
  @description
end

#fetch_missing_argsObject (readonly)

Returns the value of attribute fetch_missing_args.



265
266
267
# File 'lib/sidekiq/cron/job.rb', line 265

def fetch_missing_args
  @fetch_missing_args
end

#klassObject

Returns the value of attribute klass.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def klass
  @klass
end

#last_enqueue_timeObject (readonly)

Returns the value of attribute last_enqueue_time.



265
266
267
# File 'lib/sidekiq/cron/job.rb', line 265

def last_enqueue_time
  @last_enqueue_time
end

#messageObject

Returns the value of attribute message.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def message
  @message
end

#nameObject

Returns the value of attribute name.



264
265
266
# File 'lib/sidekiq/cron/job.rb', line 264

def name
  @name
end

Class Method Details

.allObject

Get all cron jobs.



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/sidekiq/cron/job.rb', line 210

def self.all
  job_hashes = nil
  Sidekiq.redis do |conn|
    set_members = conn.smembers(jobs_key)
    job_hashes = conn.pipelined do |pipeline|
      set_members.each do |key|
        pipeline.hgetall(key)
      end
    end
  end
  job_hashes.compact.reject(&:empty?).collect do |h|
    # No need to fetch missing args from Redis since we just got this hash from there
    Sidekiq::Cron::Job.new(h.merge(fetch_missing_args: false))
  end
end

.countObject



226
227
228
229
230
231
232
# File 'lib/sidekiq/cron/job.rb', line 226

def self.count
  out = 0
  Sidekiq.redis do |conn|
    out = conn.scard(jobs_key)
  end
  out
end

.create(hash) ⇒ Object

Create new instance of cron job.



248
249
250
# File 'lib/sidekiq/cron/job.rb', line 248

def self.create hash
  new(hash).save
end

.destroy(name) ⇒ Object

Destroy job by name.



253
254
255
256
257
258
259
260
261
262
# File 'lib/sidekiq/cron/job.rb', line 253

def self.destroy name
  # If name is hash try to get name from it.
  name = name[:name] || name['name'] if name.is_a?(Hash)

  if job = find(name)
    job.destroy
  else
    false
  end
end

.destroy_all!Object

Remove all job from cron.



521
522
523
524
525
526
# File 'lib/sidekiq/cron/job.rb', line 521

def self.destroy_all!
  all.each do |job|
    job.destroy
  end
  Sidekiq.logger.info { "Cron Jobs - deleted all jobs" }
end

.destroy_removed_jobs(new_job_names) ⇒ Object

Remove “removed jobs” between current jobs and new jobs



529
530
531
532
533
534
# File 'lib/sidekiq/cron/job.rb', line 529

def self.destroy_removed_jobs new_job_names
  current_job_names = Sidekiq::Cron::Job.all.map(&:name)
  removed_job_names = current_job_names - new_job_names
  removed_job_names.each { |j| Sidekiq::Cron::Job.destroy(j) }
  removed_job_names
end

.exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


550
551
552
553
554
555
# File 'lib/sidekiq/cron/job.rb', line 550

def self.exists? name
  out = Sidekiq.redis do |conn|
    conn.public_send(REDIS_EXISTS_METHOD, redis_key(name))
  end
  out == true || out == 1
end

.find(name) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/sidekiq/cron/job.rb', line 234

def self.find name
  # If name is hash try to get name from it.
  name = name[:name] || name['name'] if name.is_a?(Hash)

  output = nil
  Sidekiq.redis do |conn|
    if exists? name
      output = Job.new conn.hgetall( redis_key(name) )
    end
  end
  output if output && output.valid?
end

.load_from_array(array) ⇒ Object

Load cron jobs from Array. Input structure should look like: [

{
  'name'        => 'name_of_job',
  'class'       => 'MyClass',
  'cron'        => '1 * * * *',
  'args'        => '(OPTIONAL) [Array or Hash]',
  'description' => '(OPTIONAL) Description of job'
},
{
  'name'  => 'Cool Job for Second Class',
  'class' => 'SecondClass',
  'cron'  => '*/5 * * * *'
}

]



192
193
194
195
196
197
198
199
# File 'lib/sidekiq/cron/job.rb', line 192

def self.load_from_array array
  errors = {}
  array.each do |job_data|
    job = new(job_data)
    errors[job.name] = job.errors unless job.save
  end
  errors
end

.load_from_array!(array) ⇒ Object

Like #load_from_array. If exists old jobs in Redis but removed from args, destroy old jobs.



203
204
205
206
207
# File 'lib/sidekiq/cron/job.rb', line 203

def self.load_from_array! array
  job_names = array.map { |job| job["name"] }
  destroy_removed_jobs(job_names)
  load_from_array(array)
end

.load_from_hash(hash) ⇒ Object

Load cron jobs from Hash. Input structure should look like: {

'name_of_job' => {
  'class'       => 'MyClass',
  'cron'        => '1 * * * *',
  'args'        => '(OPTIONAL) [Array or Hash]',
  'description' => '(OPTIONAL) Description of job'
},
'My super iber cool job' => {
  'class' => 'SecondClass',
  'cron'  => '*/5 * * * *'
}

}



160
161
162
163
164
165
166
# File 'lib/sidekiq/cron/job.rb', line 160

def self.load_from_hash hash
  array = hash.map do |key, job|
    job['name'] = key
    job
  end
  load_from_array array
end

.load_from_hash!(hash) ⇒ Object

Like #load_from_hash. If exists old jobs in Redis but removed from args, destroy old jobs.



170
171
172
173
# File 'lib/sidekiq/cron/job.rb', line 170

def self.load_from_hash! hash
  destroy_removed_jobs(hash.keys)
  load_from_hash(hash)
end

Instance Method Details

#active_job_messageObject

Active Job has different structure how it is loading data from Sidekiq queue, it creates a wrapper around job.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/sidekiq/cron/job.rb', line 130

def active_job_message
  {
    'class'        => 'ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper',
    'wrapped'      => @klass,
    'queue'        => @queue_name_with_prefix,
    'description'  => @description,
    'args'         => [{
      'job_class'  => @klass,
      'job_id'     => SecureRandom.uuid,
      'queue_name' => @queue_name_with_prefix,
      'arguments'  => enqueue_args
    }]
  }
end

#add_jid_history(jid) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/sidekiq/cron/job.rb', line 487

def add_jid_history(jid)
  jid_history = {
    jid: jid,
    enqueued: @last_enqueue_time
  }

  @history_size ||= (Sidekiq::Options[:cron_history_size] || 10).to_i - 1
  Sidekiq.redis do |conn|
    conn.lpush jid_history_key,
               Sidekiq.dump_json(jid_history)
    # Keep only last 10 entries in a fifo manner.
    conn.ltrim jid_history_key, 0, @history_size
  end
end

#date_as_argument?Boolean

Returns:

  • (Boolean)


83
84
85
# File 'lib/sidekiq/cron/job.rb', line 83

def date_as_argument?
  !!@date_as_argument
end

#destroyObject



502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/sidekiq/cron/job.rb', line 502

def destroy
  Sidekiq.redis do |conn|
    # Delete from set.
    conn.srem self.class.jobs_key, [redis_key]

    # Delete runned timestamps.
    conn.del job_enqueued_key

    # Delete jid_history.
    conn.del jid_history_key

    # Delete main job.
    conn.del redis_key
  end

  Sidekiq.logger.info { "Cron Jobs - deleted job with name: #{@name}" }
end

#disable!Object



343
344
345
346
# File 'lib/sidekiq/cron/job.rb', line 343

def disable!
  @status = "disabled"
  save
end

#disabled?Boolean

Returns:

  • (Boolean)


357
358
359
# File 'lib/sidekiq/cron/job.rb', line 357

def disabled?
  !enabled?
end

#enable!Object



348
349
350
351
# File 'lib/sidekiq/cron/job.rb', line 348

def enable!
  @status = "enabled"
  save
end

#enabled?Boolean

Returns:

  • (Boolean)


353
354
355
# File 'lib/sidekiq/cron/job.rb', line 353

def enabled?
  @status == "enabled"
end

#enque!(time = Time.now.utc) ⇒ Object

Enqueue cron job to queue.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/sidekiq/cron/job.rb', line 47

def enque! time = Time.now.utc
  @last_enqueue_time = time.strftime(LAST_ENQUEUE_TIME_FORMAT)

  klass_const =
      begin
        Sidekiq::Cron::Support.constantize(@klass.to_s)
      rescue NameError
        nil
      end

  jid =
    if klass_const
      if defined?(ActiveJob::Base) && klass_const < ActiveJob::Base
        enqueue_active_job(klass_const).try :provider_job_id
      else
        enqueue_sidekiq_worker(klass_const)
      end
    else
      if @active_job
        Sidekiq::Client.push(active_job_message)
      else
        Sidekiq::Client.push(sidekiq_worker_message)
      end
    end

  save_last_enqueue_time
  add_jid_history jid
  Sidekiq.logger.debug { "enqueued #{@name}: #{@message}" }
end

#enqueue_active_job(klass_const) ⇒ Object



91
92
93
# File 'lib/sidekiq/cron/job.rb', line 91

def enqueue_active_job(klass_const)
  klass_const.set(queue: @queue).perform_later(*enqueue_args)
end

#enqueue_argsObject



87
88
89
# File 'lib/sidekiq/cron/job.rb', line 87

def enqueue_args
  date_as_argument? ? @args + [Time.now.to_f] : @args
end

#enqueue_sidekiq_worker(klass_const) ⇒ Object



95
96
97
# File 'lib/sidekiq/cron/job.rb', line 95

def enqueue_sidekiq_worker(klass_const)
  klass_const.set(queue: queue_name_with_prefix).perform_async(*enqueue_args)
end

#errorsObject



418
419
420
# File 'lib/sidekiq/cron/job.rb', line 418

def errors
  @errors ||= []
end

#exists?Boolean

Returns:

  • (Boolean)


557
558
559
# File 'lib/sidekiq/cron/job.rb', line 557

def exists?
  self.class.exists? @name
end

#formatted_enqueue_time(now = Time.now.utc) ⇒ Object



542
543
544
# File 'lib/sidekiq/cron/job.rb', line 542

def formatted_enqueue_time now = Time.now.utc
  last_time(now).getutc.to_f.to_s
end

#formatted_last_time(now = Time.now.utc) ⇒ Object



546
547
548
# File 'lib/sidekiq/cron/job.rb', line 546

def formatted_last_time now = Time.now.utc
  last_time(now).getutc.iso8601
end

#is_active_job?Boolean

Returns:

  • (Boolean)


77
78
79
80
81
# File 'lib/sidekiq/cron/job.rb', line 77

def is_active_job?
  @active_job || defined?(ActiveJob::Base) && Sidekiq::Cron::Support.constantize(@klass.to_s) < ActiveJob::Base
rescue NameError
  false
end

#jid_history_from_redisObject



388
389
390
391
392
393
394
395
396
397
# File 'lib/sidekiq/cron/job.rb', line 388

def jid_history_from_redis
  out =
    Sidekiq.redis do |conn|
      conn.lrange(jid_history_key, 0, -1) rescue nil
    end

  out && out.map do |jid_history_raw|
    Sidekiq.load_json jid_history_raw
  end
end

#klass_validObject



450
451
452
453
454
455
456
457
458
# File 'lib/sidekiq/cron/job.rb', line 450

def klass_valid
  case @klass
    when Class
      true
    when String
      @klass.size > 0
    else
  end
end

#last_enqueue_time_from_redisObject



378
379
380
381
382
383
384
385
386
# File 'lib/sidekiq/cron/job.rb', line 378

def last_enqueue_time_from_redis
  out = nil
  if fetch_missing_args
    Sidekiq.redis do |conn|
      out = parse_enqueue_time(conn.hget(redis_key, "last_enqueue_time")) rescue nil
    end
  end
  out
end

#last_time(now = Time.now.utc) ⇒ Object

Parse cron specification ‘* * * * *’ and returns time when last run should be performed



538
539
540
# File 'lib/sidekiq/cron/job.rb', line 538

def last_time now = Time.now.utc
  parsed_cron.previous_time(now.utc).utc
end

#pretty_messageObject



361
362
363
364
365
# File 'lib/sidekiq/cron/job.rb', line 361

def pretty_message
  JSON.pretty_generate Sidekiq.load_json(message)
rescue JSON::ParserError
  message
end

#queue_name_with_prefixObject



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/sidekiq/cron/job.rb', line 106

def queue_name_with_prefix
  return @queue unless is_active_job?

  if !"#{@active_job_queue_name_delimiter}".empty?
    queue_name_delimiter = @active_job_queue_name_delimiter
  elsif defined?(ActiveJob::Base) && defined?(ActiveJob::Base.queue_name_delimiter) && !ActiveJob::Base.queue_name_delimiter.empty?
    queue_name_delimiter = ActiveJob::Base.queue_name_delimiter
  else
    queue_name_delimiter = '_'
  end

  if !"#{@active_job_queue_name_prefix}".empty?
    queue_name = "#{@active_job_queue_name_prefix}#{queue_name_delimiter}#{@queue}"
  elsif defined?(ActiveJob::Base) && defined?(ActiveJob::Base.queue_name_prefix) && !"#{ActiveJob::Base.queue_name_prefix}".empty?
    queue_name = "#{ActiveJob::Base.queue_name_prefix}#{queue_name_delimiter}#{@queue}"
  else
    queue_name = @queue
  end

  queue_name
end

#remove_previous_enques(time) ⇒ Object

Remove previous information about run times, this will clear Redis and make sure that Redis will not overflow with memory.



31
32
33
34
35
# File 'lib/sidekiq/cron/job.rb', line 31

def remove_previous_enques time
  Sidekiq.redis do |conn|
    conn.zremrangebyscore(job_enqueued_key, 0, "(#{(time.to_f - REMEMBER_THRESHOLD).to_s}")
  end
end

#saveObject



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/sidekiq/cron/job.rb', line 460

def save
  # If job is invalid, return false.
  return false unless valid?

  Sidekiq.redis do |conn|

    # Add to set of all jobs
    conn.sadd self.class.jobs_key, [redis_key]

    # Add informations for this job!
    conn.hmset redis_key, *hash_to_redis(to_hash)

    # Add information about last time! - don't enque right after scheduler poller starts!
    time = Time.now.utc
    exists = conn.public_send(REDIS_EXISTS_METHOD, job_enqueued_key)
    conn.zadd(job_enqueued_key, time.to_f.to_s, formatted_last_time(time).to_s) unless exists == true || exists == 1
  end
  Sidekiq.logger.info { "Cron Jobs - added job with name: #{@name}" }
end

#save_last_enqueue_timeObject



480
481
482
483
484
485
# File 'lib/sidekiq/cron/job.rb', line 480

def save_last_enqueue_time
  Sidekiq.redis do |conn|
    # Update last enqueue time.
    conn.hset redis_key, 'last_enqueue_time', @last_enqueue_time
  end
end

#should_enque?(time) ⇒ Boolean

Crucial part of whole enqueuing job.

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
# File 'lib/sidekiq/cron/job.rb', line 19

def should_enque? time
  enqueue = Sidekiq.redis do |conn|
    status == "enabled" &&
      not_past_scheduled_time?(time) &&
      not_enqueued_after?(time) &&
      conn.zadd(job_enqueued_key, formatted_enqueue_time(time), formatted_last_time(time))
  end
  enqueue == true || enqueue == 1
end

#sidekiq_worker_messageObject

Sidekiq worker message.



100
101
102
103
104
# File 'lib/sidekiq/cron/job.rb', line 100

def sidekiq_worker_message
  message = @message.is_a?(String) ? Sidekiq.load_json(@message) : @message
  message["args"] = enqueue_args
  message
end

#sort_nameObject



561
562
563
# File 'lib/sidekiq/cron/job.rb', line 561

def sort_name
  "#{status == "enabled" ? 0 : 1}_#{name}".downcase
end

#statusObject



339
340
341
# File 'lib/sidekiq/cron/job.rb', line 339

def status
  @status
end

#status_from_redisObject



367
368
369
370
371
372
373
374
375
376
# File 'lib/sidekiq/cron/job.rb', line 367

def status_from_redis
  out = "enabled"
  if fetch_missing_args
    Sidekiq.redis do |conn|
      status = conn.hget redis_key, "status"
      out = status if status
    end
  end
  out
end

#test_and_enque_for_time!(time) ⇒ Object

Test if job should be enqueued.



38
39
40
41
42
43
44
# File 'lib/sidekiq/cron/job.rb', line 38

def test_and_enque_for_time! time
  if should_enque?(time)
    enque!

    remove_previous_enques(time)
  end
end

#to_hashObject

Export job data to hash.



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/sidekiq/cron/job.rb', line 400

def to_hash
  {
    name: @name,
    klass: @klass.to_s,
    cron: @cron,
    description: @description,
    args: @args.is_a?(String) ? @args : Sidekiq.dump_json(@args || []),
    date_as_argument: date_as_argument? ? "1" : "0",
    message: @message.is_a?(String) ? @message : Sidekiq.dump_json(@message || {}),
    status: @status,
    active_job: @active_job ? "1" : "0",
    queue_name_prefix: @active_job_queue_name_prefix,
    queue_name_delimiter: @active_job_queue_name_delimiter,
    last_enqueue_time: @last_enqueue_time.to_s,
    symbolize_args: symbolize_args? ? "1" : "0",
  }
end

#valid?Boolean

Returns:

  • (Boolean)


422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/sidekiq/cron/job.rb', line 422

def valid?
  # Clear previous errors.
  @errors = []

  errors << "'name' must be set" if @name.nil? || @name.size == 0
  if @cron.nil? || @cron.size == 0
    errors << "'cron' must be set"
  else
    begin
      c = Fugit.do_parse(@cron)

      # Since `Fugit.do_parse` might yield a Fugit::Duration or an EtOrbi::EoTime
      # https://github.com/floraison/fugit#fugitparses
      if c.is_a?(Fugit::Cron)
        @parsed_cron = c
      else
        errors << "'cron' -> #{@cron.inspect} -> not a cron but a #{c.class}"
      end
    rescue => e
      errors << "'cron' -> #{@cron.inspect} -> #{e.class}: #{e.message}"
    end
  end

  errors << "'klass' (or class) must be set" unless klass_valid

  errors.empty?
end