Pabi
Pabi

Reputation: 994

In Rails, how to make random events happen at random times for random users

I am looking for a way to make a couple of predefined events as methods happen at random times for random users.

Please let me know if I am not clear enough.

Upvotes: 2

Views: 134

Answers (1)

Omar Lahlou
Omar Lahlou

Reputation: 1000

You have to create ActiveJobs and rake tasks that will fire them. Example: In app/jobs, create a share_job.rb with the following code:

require "active_job"
class ShareJob < ActiveJob::Base
  def perform
    func_to_call = rand(n) # n is the number of methods you have
    case func_to_call
    when 0
      # call first_func
    when 1
      # call second_func
    #...
  end
end

Then in lib/tasks, create an execute_job.rakefile with the following code:

namespace :execute do
  task execute_random_function: :environment do
    ShareJob.perform_later()
  end
end

To run this code manually, type in your console:

rake execute:execute_random_function

You can execute this job at a random time using Scheduler(a Heroku Add-on)

Upvotes: 3

Related Questions