Rails ActiveJob 从控制器启动
Rails ActiveJob Start From Controller
我有一些自定义代码可以调用一些后端系统并远程更新数据库。我有一个执行任务的 ActiveJob:
## Runs join code
class DataJoin < ApplicationJob
queue_as :default
def perform
join = Joiner.new
join.run
NotifMailer.sample_email.deliver_now
end
end
我想从 controller/view:
手动启动 ActiveJob
class AdminController < ApplicationController
before_action :verify_is_admin
private def verify_is_admin
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end
def index
@username = current_user.name
@intro = "Welcome to the admin console"
end
def join
## Code to start ActiveJob DataJoin??
end
end
如何从控制器启动 ActiveJob?
试试这个:
DataJoin.perform_later
perform_later
将作业排入指定队列。如果您的活动作业的 perform
方法接受一些参数,您甚至可以将它们传递给 perform_later
,这些参数将在执行时可用。
DataJoin.perform_later(1, 2, 3)
# DataJoin
def perform(a1, a2, a3)
# a1 will be 1
# a2 will be 2
# a3 will be 3
end
请阅读official guide on ActiveJob
def join
DataJoin.perform_later
end
我有一些自定义代码可以调用一些后端系统并远程更新数据库。我有一个执行任务的 ActiveJob:
## Runs join code
class DataJoin < ApplicationJob
queue_as :default
def perform
join = Joiner.new
join.run
NotifMailer.sample_email.deliver_now
end
end
我想从 controller/view:
手动启动 ActiveJobclass AdminController < ApplicationController
before_action :verify_is_admin
private def verify_is_admin
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end
def index
@username = current_user.name
@intro = "Welcome to the admin console"
end
def join
## Code to start ActiveJob DataJoin??
end
end
如何从控制器启动 ActiveJob?
试试这个:
DataJoin.perform_later
perform_later
将作业排入指定队列。如果您的活动作业的 perform
方法接受一些参数,您甚至可以将它们传递给 perform_later
,这些参数将在执行时可用。
DataJoin.perform_later(1, 2, 3)
# DataJoin
def perform(a1, a2, a3)
# a1 will be 1
# a2 will be 2
# a3 will be 3
end
请阅读official guide on ActiveJob
def join
DataJoin.perform_later
end