Is it possible to access Models in schedule.rb (whenever gem)? - ruby-on-rails

I am performing some tests in a Ruby on Rails application using Whenever gem.
Is it possible to access Models from the schedule.rb file ?!
For example:
#Hard Worker
job = Job.find_by(name: 'Hard')
if job.status == 'active'
every 4.minutes do
runner 'HardWorker.perform_async'
end
end
Just checked this and I encountered this error:
config/schedule.rb:2:in `initialize': undefined method `find_by' for Whenever::Job:Class (NoMethodError)
Many thanks !

Related

How to run a resque job in the console?

I am trying to call a job in the console but always get errors.
Followed the following documentation:
http://tutorials.jumpstartlab.com/topics/performance/background_jobs.html
https://www.youtube.com/watch?v=UrE47tCrZXc
https://guides.rubyonrails.org/active_job_basics.html
https://github.com/resque/resque
How can I run an ActiveJob in Rails console for debugging?
Created the following file:
(lib/jobs/archive_survey_jobs.rb)
module Jobs
class ArchiveSurveysJob < ActiveJob::Base
#queue = :setup
def perform(survey_type)
if SurveyTypes.all_classes.map(&:to_s).include?(survey_type)
surveys = Survey.where(something: 'stuff')\
.where.not(something: 'stuff',
something: 'stuff')
surveys.each do |survey|
do_something
end
end
end
end
end
I understand that I can do something like Resque.enqueue(ArchiveSurveysJob, 'string_here')
How can I call this in the console? If I try:
Jobs::ArchiveSurveysJob.create(survey_type: 'string_here'),
when I check the Resque Statuses it resulted in an error: `The task failed because of an error:
undefined local variable or method `args' for #
If I try this:
Jobs::ArchiveSurveysJob.perform(`string_here`)
Or:
Jobs::ArchiveSurveysJob.perform_now('string_here')
I get:
ArgumentError: wrong number of arguments (given 0, expected 1..2)
Please let me know if I am missing some documentation or if I am doing something wrong.
In your example, perform is an instance method. youre calling the class level perform which might not have any arguments. I dont know about your version of resque specifically, however you can enqueue jobs from the console like this in at least one version: Resque.enqueue(Jobs::ArchiveSurveysJob)
ps, make sure your resque workers are running.
In dev environments I typically have resque running in line:
# config/initializers/resque.rb
Resque.inline = true if Rails.env.dev? || Rails.env.test?
How I managed to do this was by creating a Rake task and calling the Job there.

Error "undefined method `to_datetime'" in sidekiq

Start sidekiq with the command
bundle exec sidekiq -e production -P /path/to/pid/file/tmp/pids/sidekiq.pid -L /path/to/log/file/shared/log/sidekiq.log --daemon
In the log error
2017-06-29T06:59:44.776Z 16181 TID-1jr7pg ERROR: CRON JOB: undefined method `to_datetime' for #<EtOrbi::EoTime:0x0000000a933848>
2017-06-29T06:59:44.776Z 16181 TID-1jr7pg ERROR: CRON JOB: /home/user/.rvm/gems/ruby-2.0.0-p247#script-admin/gems/activesupport-3.2.13/lib/active_support/core_ext/date_time/calculations.rb:141:in `<=>'
error while executing the method /home/user/.rvm/gems/ruby-2.0.0-p247#script-admin/gems/activesupport-3.2.13/lib/active_support/core_ext/date_time/calculations.rb:141:in <=>:
def <=> (other)
super other.kind_of?(Infinity) ? other : other.to_datetime
end
What can be done with the problem?
UPD: Updated version rails to 3.2.22.5 and there is a new error
ERROR: CRON JOB: comparison of Time with EtOrbi::EoTime failed
ERROR: CRON JOB: /home/user/.rvm/gems/ruby-2.0.0-p247#script-admin/gems/sidekiq-cron-0.3.1/lib/sidekiq/cron/job.rb:434:in `<'
in this place
def not_enqueued_after?(time)
#last_enqueue_time.nil? || #last_enqueue_time < last_time(time)
end
Your issue arises not from sidekiq but from Rails 3.2.13. #<=> does not handle undefined method to_datetime. It was fixed in future versions of Rails. For example, in the Rails 3.2.22.5:
def <=>(other)
if other.kind_of?(Infinity)
super
elsif other.respond_to? :to_datetime
super other.to_datetime
else
nil
end
end
Therefore, the simplest way to solve your issue is to update your Rails version. If it is not an options paste your code or rewrite #<=>.
to_datetime is a method from rails' activesupport library and your sidekiq worker is not using this.
try adding require 'active_support/core_ext' to your sidekiq initializer config config/initializers/sidekiq.rb and restart sidekiq

uninitialized constant SampleController::Delayed while executing delayed_job worker method

I am getting the following error while executing SampleController.
uninitialized constant IdeasController::Delayed
I have already started the delayed_job by using rake jobs:work. I have the following delayed_job code in SampleController.rb
Delayed::Job.enqueue(DelayedWorker.new({:model=>object.class.to_s,:object_id=>object.id,:meth=>:create_suggestion}))
delayed_worker.rb contains the following code:
class DelayedWorker < Struct.new(:options)
def perform
if obj=Object.const_get(options[:model]).find(options[:object_id])
if (options[:para] ? obj.send(options[:meth],options[:para].first) : obj.send(options[:meth]))
puts "Successfull"
else
puts "Failed"
end
end
end
end
Any one please help me for resolving this.
Thanks...
Change
Delayed::Job.enqueue(DelayedWorker.new({:model=>object.class.to_s,:object_id=>object.id,:meth=>:create_suggestion}))
to
::Delayed::Job.enqueue(DelayedWorker.new({:model=>object.class.to_s,:object_id=>object.id,:meth=>:create_suggestion}))

Resque worker not recognizing the Rails Mongoid model

I am using resque in my application for delayed jobs, where i cant send emails & sms to bulk number of users asynchronously. And the data is stored in mongodb, mongoid is the ODM connects rails & mongo.
My mongoid model looks like this
class Item
include Mongoid::Document
include Geo::LocationHelper
field :name, :type => String
field :desc, :type => String
#resque queue name
#queue = :item_notification
#resque perform method
def self.perform(item_id)
#item = Item.find(item_id)
end
end
I can able to add jobs to resque, i have verified using resque-web. Whenever i start an resque-worker
QUEUE=item_notification rake resque:work
i got the uninitialized constant Item , since i am using resque as rails gem and starting rake in rails root, i believe my mongoid models should be loaded.
After digging lot, i found that we can explicitly ask rake to load the environment by
QUEUE=item_notification rake environment resque:work
but now also i got the same error uninitialized constant Item
can someone help me out?
and my
Actually, its a problem in dev environment. after adding this line to into resque.rake task file
# load the Rails app all the time
namespace :resque do
puts "Loading Rails environment for Resque"
task :setup => :environment
ActiveRecord::Base.send(:descendants).each { |klass| klass.columns }
end
it works fine
The code taken from GitHub-Resque-Wiki

Delayed_job in rails failing

I am just beginning to look into using the delayed_job gem.
To test it, I added "delayed" to the welcome email function and changed that call from
UserMailer.welcome_email(self).deliver
to
UserMailer.delay.welcome_email(self)
This is called inside the User model after_create. I see an entry show up in the delayed_job table after the function executes. Now when I run "rake jobs:work" on command line the task starts but gives errors as below
[Worker(host:Sanjay-PC pid:7008)] Starting job worker
[Worker(host:Sanjay-PC pid:7008)] Class#welcome_email failed with NoMethodError: undefined method `welcome_email' for #<Class:0x4871d60> - 0 failed attempts
[Worker(host:Sanjay-PC pid:7008)] 1 jobs processed at 0.0939 j/s, 1 failed ...
Thinking that if I changed the welcome_email method declaration to a Class method as
def self.welcome_email(user)
(added self. in front) that might help. But then when I run rake jobs:work I get the following error
rake aborted!
undefined method `welcome_email' for class `UserMailer'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method_chain'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/delayed_job-2.1.4/lib/delayed/message_sending.rb:50:in `handle_asynchronously'
c:/mgn/mgn-r3/app/mailers/user_mailer.rb:10:in `<class:UserMailer>'
c:/mgn/mgn-r3/app/mailers/user_mailer.rb:1:in `<top (required)>'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load'
<Stack truncated>
It seems to now know the class as UserMailer but it somehow doesn't see the class method welcome_email.
I am on Rails 3.0.5, Ruby 1.9.2p180 and the installed delayed_job gem is 2.1.4 - on Windows
Can't seem to find any related answers anywhere.
Thanks for your thoughts.
-S
Adding UserMailer code per #pjammer's request
class UserMailer < ActionMailer::Base
default :from => "from#example.com"
def welcome_email(user)
#user = user
#url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
Just use this
UserMailer.delay.welcome_email(self).deliver
instead of
UserMailer.welcome_email(self).delay.deliver
My solution was to redefine function at the handler class (for you it's UserMailer class)
def self.taguri
'tag:ruby.yaml.org,2002:class'
end
It's a hack and I'll try to find a better solution but now it works for me.
(Rails 3.0.9, Ruby 1.9.2-p290, delayed_job 2.1.4)
https://groups.google.com/forum/?fromgroups=#!topic/delayed_job/_gvIcbXrOaE solved my handles_asynchronously error for class methods.
As per Brandon Keeper in the link above, the code is the following:
class ClassName
class << self
def foo
end
handle_asynchronously :foo
end
end
then use ClassName.delay.foo

Resources