Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails whenver gem , running a command only if certain condition passes.

We are using whenever gem with rails on our project. I understand that we can schedule a command using whenever gem like this.

every 1.day, :at => '6:00 am' do
  command "echo 'hello'"
end

but my problem is that i want to execute this command only when some condition is met. something like this.

every 1.day, :at => '6:00 am' do
 if User.any_new_user? 
  command "echo 'hello'"
 end
end

how can we achieve this with the whenever and rails? One possible solution i can think of is that i create a runner for this and check that condition there.Something like:

every 1.day, :at => '6:00 am' do
  runner "User.say_conditional_hello"
end

and inside my user model:

def self.say_conditional_hello
    `echo "Hello"`
end  

Any suggestions on this approach or any new approach will be really helpful.

Thanks in advance!.

like image 334
Sahil Dhankhar Avatar asked Nov 01 '22 16:11

Sahil Dhankhar


1 Answers

if you want to only schedule the task if the condition is true then I don't think its possible you can schedule a task then when its time for running the task, the code can decide if it should be run or not, depending on your conditions

One possible solution i can think of is that i create a runner for this and check that condition there.Something like:

Yes this is one way of handeling this, however IMO the best behavior when using whenever is creating a rake task that checks for conditions then executes your code or perform your job

Something like:

Rake Task

namespace :user do
  desc "description"
  task check_for_new: :environment do
    if User.any_new_user? 
      # code
    end
  end
end 

in your schedule.rb file

every 1.day, :at => '6:00 am' do
  rake "user:check_for_new"
end
like image 190
Mshka Avatar answered Nov 07 '22 23:11

Mshka