ActiveJob Schedule in Rails
I am making a weather API that will receive, process and save data from another API. To get daily updates (query url information, get JSON / XML data, create my data and store it in my database), I find the most appropriate way is to use an ActiveJob.
I want the task to run periodically. I would like something like UNIX cron or Spring @Scheduled annotations for Java.
I've seen a few more Stack Overflow questions ( this one ) about job scheduling, but they use external gems like they ever did. I was looking for a backend that allows work to be done in the Rails API ( Backends ), but it seems that none of the available ones allow work scheduling.
Is there anything in the Rails framework (version 5) that allows me to do what I am trying to do? Or should I use an external stone?
Thank you very much.
Edit If this is useful to everyone, here is the outline for the job:
class ImportDailyDataJob < ApplicationJob
queue_as :default
def perform(*args)
# Do something later
end
private
def prepare_request
# return the request object
end
def request_data
# Get the data from external API.
end
def process_data
# Process the data
end
def save_processed_data
# Saves the data to the database
end
end
source to share
This is not real planning, but you can fake it in certain situations if you don't want the planning to be completely accurate, i.e. in your case, do the task once a day:
class WeatherJob < ApplicationJob
def perform
reschedule_job
do_work
end
def do_work
# ...
end
def reschedule_job
self.class.set(wait: 24.hours).perform_later
end
end
enqueuing jobs to run in the future using ActiveJob should work with DelayedJob or Sidekiq, perhaps not supported on all active work servers?
source to share
Most of the major AJ adapters have some functionality for scheduling jobs, but some are split into separate gems. For example, for Resque there is a separate resque-scheduler stone that works with the vanilla Resque stone for this very purpose.
And here's the bit about repetitive assignments. After some basic setup, you create a schedule.yml file that defines how / when you want your work to be done, eg.
# config/initializers/resque_scheduler.rb
Resque.schedule = YAML.load_file('../calendar.yml')
# config/calendar.yml
your_recurring_job:
cron: "0 0 * * *" # Every day at midnight
class: "YourJobClass"
queue: your_queue
args:
description: "This job does a thing, daily"
I don't know about every adapter, but the main ones usually have similar sisters that provide this functionality.
source to share