DEV Community

Masashi Salvador Mitsuzawa
Masashi Salvador Mitsuzawa

Posted on

Writing Serial Process with Active Job

I am using Active Job in Rails for writing Job Queue, I wrote some jobs that issues SQLs and writing data in temporary table, then I'd like to write a whole processor job that serially executes job1, job2, job3...., and jobN and completed a calculation task.

then, in ActiveJob, we have two methods:

job.perform_later() # asynchronous
job.perform_now() # wait for finishing.
Enter fullscreen mode Exit fullscreen mode

so, in my case perform_now is a solution.

Serializaed process with ActiveJob

# this Job is sleeper
class Job1Job < ApplicationJob
  queue_as :default

  def perform()
    puts "hello1"
    sleep(5)
    puts "after sleep"
  end
end
Enter fullscreen mode Exit fullscreen mode
# this Job won't sleep
class Job2Job < ApplicationJob
  queue_as :default

  def perform()
    puts "hello2"
  end
end
Enter fullscreen mode Exit fullscreen mode
# this job is a manager
class Job3Job < ApplicationJob
  queue_as :default

  def perform()
    Job1Job.perform_now()
    Job2Job.perform_now()
    puts "hoge"
  end
end
Enter fullscreen mode Exit fullscreen mode

the result of execution in rails console.

> Job3Job.perform_later()
Enter fullscreen mode Exit fullscreen mode

then we obtain

# bundle exec rake jobs:work
hello1
after sleep
hello2
hoge
Enter fullscreen mode Exit fullscreen mode

:)

Top comments (0)