I am using Sidekiq
on my gemfile I have:
#gemfile
gem 'sidekiq', '~> 6.0.7'
Now my model looks like
class Special < ActiveRecord::Base
def set_queue
if send_at.present? # send at is a data time
SpecialQueueClientsJob.perform_at(self.send_at, self)
end
end
end
This is the code to my job and this works perfect when I just call it normally SpecialQueueClientsJob.perform_later(special: self)
class SpecialQueueClientsJob < ApplicationJob
queue_as :default
def perform(special)
...
end
end
https://github.com/mperham/sidekiq
I am getting an error undefined method perform_at' for SpecialQueueClientsJob `
I am looking at https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs
Sidekiq allows you to schedule the time when a job will be executed.
You use perform_in(interval_in_seconds, *args) or
perform_at(timestamp, *args) rather than the standard
perform_async(*args):
MyWorker.perform_in(3.hours, 'mike', 1)
MyWorker.perform_at(3.hours.from_now, 'mike', 1) This is useful for
example if you want to send the user an email 3 hours after they sign
up. Jobs which are scheduled in the past are enqueued for immediate
execution.
Related
I am using the most basic version of delayed_job in a Rails app. I have the max time allowed for a delayed_job set at 10 minutes. I would like to get the hooks/callbacks working so I can do something after a job stop executing at the 10 minute mark.
I have this set in my rails app:
config.active_job.queue_adapter = :delayed_job
This is how I normally queue a job:
object.delay.object_action
The hook/callback example is for a named job but the basic, getting started steps are not for a named job. So I don't think I have a named job. Here is the example given to get the callbacks working:
class ParanoidNewsletterJob < NewsletterJob
def enqueue(job)
record_stat 'newsletter_job/enqueue'
end
def perform
emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) }
end
def before(job)
record_stat 'newsletter_job/start'
end
def after(job)
record_stat 'newsletter_job/after'
end
def success(job)
record_stat 'newsletter_job/success'
end
def error(job, exception)
Airbrake.notify(exception)
end
def failure(job)
page_sysadmin_in_the_middle_of_the_night
end
end
I would love to get the after or error hooks/callbacks to fire.
Where do I put these callbacks in my Rails app to have them fire for the basic delayed_job setup? If I should be using ActiveJob callbacks where do you put those callbacks given delayed_job is being used?
You cannot use object.delay.object_action convenience syntax if you want more advanced features like callbacks. The #delay convenience method will generate a job object that works similar to this:
# something like this is already defined in delayed_job
class MethodCallerJob
def initialize(object, method, *args)
#object = object
#method = method
#args = args
end
def perform
#object.send(#method, *#args)
end
end
# `object.delay.object_action` does the below automatically for you
# instantiates a job with your object and method call
job = MethodCallerJob.new(object, :object_action, [])
Delayed::Job.enqueue(job) # enqueues it for running later
then later, in the job worker, something like the below happens:
job = Delayed::Job.find(job_id) # whatever the id turned out to be
job.invoke_job # does all the things, including calling #perform and run any hooks
job.delete # if it was successful
You have to create what the delayed_job README calls "Custom Jobs", which are just plain POROs that have #perform defined at a minimum. Then you can customize it and add all the extra methods that delayed_job uses for extra features like max_run_time, queue_name, and the ones you want to use: callbacks & hooks.
Sidenote: The above info is for using delayed_job directly. All of the above is possible using ActiveJob as well. You just have to do it the ActiveJob way by reading the documentation & guides on how, just as I've linked you to the delayed_job README, above.
You can create delayed_job hooks/callback by something like this
module Delayed
module Plugins
class TestHooks < Delayed::Plugin
callbacks do |lifecycle|
lifecycle.before(:perform) do |_worker, job|
.....
end
end
end
end
end
And need this plugin to initializer
config/initializers/delayed_job.rb
require_relative 'path_to_test_plugin'
Delayed::Worker.plugins << Delayed::Plugins::TestHooks
Similar to perform there are also hooks for success failure and error.
And similar to 'before' you can also capture the 'after' hooks.
I have been using delayed_job_active_record gem in my application, in one of my use-case i have to use one hook to send an other email after the delayed job done. https://github.com/collectiveidea/delayed_job#hooks, how can i override that in my application?.
Currently i am calling in this way
do_maintenance.delay(run_at: time).change_all_parts(batch_no)
do_maintenance is the model
Hooks from this gem provide callbacks to the job, but not to the model. But you can define custom callback in the model. That callback will be called after the delayed method:
class DoMaintenance < ApplicationRecord
extend ActiveModel::Callbacks
define_model_callbacks :change_all_parts, :only => [:after]
after_change_all_parts :notify
def change_all_parts
run_callbacks :change_all_parts do
#your delayed method
end
end
handle_asynchronously :change_all_parts
def notify
#your code
end
end
I've implemented Ahoy for tracking events inside my application and I want to move the processing into a background job.
My setup works fine when I call perform_now (the job gets processed), but changing to perform_later doesn't work. From the logs, it seems the job doesn't even get enqueued.
config/initializers/ahoy.rb
class Ahoy::Store < Ahoy::BaseStore
def track_visit(data)
AhoyTrackVisitJob.perform_later(#options, data)
end
def track_event(data)
AhoyTrackEventJob.perform_later(#options, data)
end
end
app/jobs/ahoy_track_event_job.rb
class AhoyTrackEventJob < ApplicationJob
queue_as :default
def perform(options, data)
Ahoy::DatabaseStore.new(options).track_event(data)
end
end
I've tried with both Sidekiq and SuckerPunch:
development.rb
config.active_job.queue_adapter = :sidekiq
I have a Rails app with 2 jobs (ImportCsvJob and ProcessCsvJob). So that I can visibly hint in the app that there are still jobs in the queue I have this helper method (inside application_helper.rb):
module ApplicationHelper
def queued_job_count
Sidekiq::Queue.new.size
end
end
Then I use it on my index controller which is then passed to the view for processing and giving the visual hint in the app.
def index
#still_have_jobs = !queued_job_count.zero?
end
However, this works when I still had 1 background Job (ImportCsvJob), but when I added the (ProcessCsvJob) it does not work anymore.
import_csv_job.rb
require 'open-uri'
class ImportCsvJob < ActiveJob::Base
queue_as :default
def perform(csv_record)
csv_record[:object_changes] = ApplicationController.helpers.generate_hash(csv_record[:object_changes])
ObjectRecord.create(csv_record)
end
end
process_csv_job.rb
class ProcessCsvJob < ActiveJob::Base
queue_as :default
def perform(csv_path)
csv_file = open(csv_path,'rb:UTF-8')
options = {
row_sep: :auto, col_sep: ",",
user_provided_headers: [:object_id, :object_type, :timestamp, :object_changes],
remove_empty_values: true,
headers_in_file: true
}
SmarterCSV.process(csv_file, options) do |array|
ImportCsvJob.perform_later(array.first)
end
end
end
and lastly, in the model where this is called:
ProcessCsvJob.perform_later(gdrive.uploaded_file_link)
When I try to debug in Rails console using Sidekiq::Queue.new.size, it still gives out 0.
Running:
redis-server
bundle exec sidekiq
A job that is executing is not enqueued anymore. The Sidekiq process has already popped it off the queue and is executing it. The queue is empty but the job is not finished yet.
So, basically I added a monitoring for sidekiq using the web interface to see what was happening:
And as I inspected, there were no enqueued tasks nor scheduled since most of the job is set to perform almost immediately (on parallel).
Thus here's my solution to know if the count of busy jobs:
module ApplicationHelper
def queued_job_count
Sidekiq::ProcessSet.new.first['busy']
end
end
and then on the index:
def index
#still_have_jobs = !queued_job_count.zero?
end
it works! :)
I used resque-scheduler for delay jobs in previous code:
Resque.enqueue_in(options[:delay].seconds, self, context)
Now I want to include resque-status to do the job but have no idea how they can work together. The latest resque-status source code supports scheduler, as in the source code:
https://github.com/quirkey/resque-status/blob/master/lib/resque/plugins/status.rb
# Wrapper API to forward a Resque::Job creation API call into a Resque::Plugins::Status call.
# This is needed to be used with resque scheduler
# http://github.com/bvandenbos/resque-scheduler
def scheduled(queue, klass, *args)
self.enqueue_to(queue, self, *args)
end
end
But I'm not sure how to use it. Shall I just call SampleJob.scheduled(queue, myclass, :delay => delay) instead of SampleJob.create(options)?
======================================================================
Also, there is Support for resque-status (and other custom jobs):
https://github.com/bvandenbos/resque-scheduler
Some Resque extensions like resque-status use custom job classes with a slightly different API signature. 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 and make it support scheduled job.
Let's pretend we have a JobWithStatus class called FakeLeaderboard
class FakeLeaderboard < Resque::JobWithStatus
def perform
# do something and keep track of the status
end
end
And then a schedule:
create_fake_leaderboards:
cron: "30 6 * * 1"
queue: scoring
custom_job_class: FakeLeaderboard
args:
rails_env: demo
description: "This job will auto-create leaderboards for our online demo and the status will update as the worker makes progress"
But it seems only for recurring jobs. I can find params of cron, but not delay. So how can I handle delayed jobs with it?
Thanks!
I had the same issue and I solved by myself by implementing a module which provide a runner for "statused" jobs.
module Resque # :nodoc:
# Module to include in your worker class to get resque-status
# and resque-scheduler integration
module ScheduledJobWithStatus
extend ActiveSupport::Concern
included do
# Include status functionalities
include Resque::Plugins::Status
end
# :nodoc:
module ClassMethods
# This method will use a custom worker class to enqueue jobs
# with resque-scheduler plugin with status support
def enqueue_at(timestamp, *args)
class_name = self.to_s # store class name since plain class object are not "serializable"
Resque.enqueue_at(timestamp, JobWithStatusRunner, class_name, *args)
end
# Identical to enqueue_at but takes number_of_seconds_from_now
# instead of a timestamp.
def enqueue_in(number_of_seconds_from_now, *args)
enqueue_at(Time.now + number_of_seconds_from_now, *args)
end
end
end
# Wrapper worker for enqueuing
class JobWithStatusRunner
# default queue for scheduling jobs with status
#queue = :delayed
# Receive jobs from {Resque::ScheduledJobWithStatus} queue them in Resque
# with support for status informations
def self.perform(status_klass, *args)
# Retrieve original worker class
klass = status_klass.to_s.constantize
# Check if supports status jobs
unless klass.included_modules.include? Resque::Plugins::Status
Rails.logger.warn("Class #{klass} doesn't support jobs with status")
return false
end
Rails.logger.debug("Enqueing jobs #{klass} with arguments #{args}")
klass.create(*args)
rescue NameError
Rails.logger.error("Unable to enqueue jobs for class #{status_klass} with args #{args}")
false
end
end
end
In this way you can enqueue your jobs with this simple syntax:
# simple worker class
class SleepJob
# This provides integrations with both resque-status and resque-scheduler
include Resque::ScheduledJobWithStatus
# Method triggered by resque
def perform
total = (options['length'] || 60).to_i
1.upto(total) { |i| at(i, total, "At #{i} of #{total}"); sleep(1) }
end
end
# run the job delayed
SleepJob.enqueue_in(5.minutes)
# or
SleepJob.enqueue_at(5.minutes.from_now)
Just drop the module in resque initializer or in lib folder. In the latter case remember to require it somewhere.
resque-scheduler will call the scheduled method on the supplied class whenever it creates the job for your workers to consume.
It also nicely passes both the queue name and class name as a string so you can create a class level method to handle scheduled job creation.
While Fabio's answer will solve the problem, it is a bit over-engineered to answer your specific question.
Assuming you have a JobWithStatus class that all of your resque-status workers inherit from, you need only add the scheduled method to it for it to work with the resque-scheduler as so:
class JobWithStatus
include Resque::Plugins::Status
def self.scheduled(queue, klass, *args)
Resque.constantize(klass).create(*args)
end
end