Afsanefda
Afsanefda

Reputation: 3339

Run a ruby on rails job every night at a specific time

I have a job like this :

class LdapSyncJob < ApplicationJob
  queue_as :default
  require 'pp'
  def perform
    users = User.all
    users.each do |user|
      user.update("Do something")
    end
  end
end

and I use delayed job for the job processing . My question is how and where to define my job to be run every night at a specific time ? Should I call my job in an action or not ? if so how can I do that ?

Upvotes: 1

Views: 2521

Answers (1)

Satishakumar Awati
Satishakumar Awati

Reputation: 3790

The delayed job mainly used for processing tasks in queue and in background. It's usually not preferred for scheduling of tasks.

For your use case you should check out whenever a ruby gem, which works with cron jobs to schedule tasks repeatedly.

I would suggest you to move logic or method call LdapSyncJob.perform() to rake task.

In config/schedule.rb, you can do something this way

ENV['RAILS_ENV'] = "#{@pre_set_variables[:environment]}"

env :PATH, ENV['PATH']

require File.expand_path(File.dirname(__FILE__) + "/environment")

set :output, "/logs/cron_log_#{ENV['RAILS_ENV']}.log"

every 1.day, :at => '02:30 am' do
    command "cd #{Rails.root}/lib/tasks && rake task_calls_peform_code"
end

Note : Don't forget to update and restart crontab using belong commands.

whenever --update-crontab app --set 'environment=production' #update crontab
service crond restart #restart crontab

Upvotes: 1

Related Questions