gpt4 book ai didi

ruby-on-rails - 如何检查 ActiveJobs 中的队列?

转载 作者:行者123 更新时间:2023-12-04 06:27:53 24 4
gpt4 key购买 nike

在将作业排入队列之前,我想检查队列并查看队列中是否已经存在具有完全相同参数的作业,在这种情况下不要将作业排入队列。但我不知道我应该如何做到这一点。是否可以?

我知道我可以使用 TestHelper 在我的测试中轻松完成。 TestHelper 依赖于我们当然不会在生产环境中使用的 TestAdapter。

多一点背景。在我们的 API 中,我们检索每个请求中的客户端版本号。我们使用 Intercom 提供支持,并希望在 Intercom 中显示应用程序版本,以便我们可以查看客户在解决支持问题时使用的版本。但是为了限制对 Intercom 的调用次数,我将每次向 Intercom 发帖的时间延迟了几分钟,并且当一个帖子被排队时,我不想将具有相同数据的新帖子排队。

我的问题与List queued tasks with ActiveJob AsyncAdapter有关但这个问题只涉及排队的工作数量。

Efficiently reschedule ActiveJob (resque/sidekiq)表明这是不可能的,我需要单独实现解决方案。

我是否可以使用 ActiveJobs 以某种方式检查队列及其中的作业,或者我是否需要跟踪我已排队的内容以及已执行的内容?

最佳答案

下面是一个未完成的实现。它目前仅支持 Sidekiq (我假设您正在使用 Sidekiq )。

注意: 仅对此进行了部分测试,因此您可能需要更新以下一些内容。如果我有时间,我稍后会全面检查。

class ActiveJob::Base
def self.where(jid: nil, arguments: [])
found_jobs = []

job_adapter = Rails.application.config.active_job.queue_adapter

case job_adapter

when :sidekiq
queue = Sidekiq::Queue.new(queue_name)

if jid.present?
job = queue.find_job(jid)

if job
# if arguments supplied, check also if args match
if arguments.present?
should_disregard_job_class = self == ActiveJob::Base
job_has_same_class = self.to_s == job.args[0]['job_class']
job_has_same_arguments = arguments == job.args[0]['arguments'][3..-1]

if (should_disregard_job_class || job_has_same_class) && job_has_same_arguments
found_jobs << job
end

else
found_jobs << job
end
end

else
# TODO: optimise below as it is slow
queue.each do |job|
should_disregard_job_class = self == ActiveJob::Base
job_has_same_class = self.to_s == job.args[0]['job_class']
job_has_same_arguments = arguments == job.args[0]['arguments'][3..-1]

if (should_disregard_job_class || job_has_same_class) && job_has_same_arguments
found_jobs << job
end
end
end

when :resque
# TODO
else
raise "TODO: missing Adapter implementation for #{job_adapter}"
end

found_jobs
end
end

用法
jobs = ActiveJob::Base.where(jid: '12345678abcdef')
jobs = MyCustomJob.where(jid: '12345678abcdef')
jobs = MyCustomJob.where(arguments: ['firstjobargumentvalue', 'secondjobargumentvalue'])

关于ruby-on-rails - 如何检查 ActiveJobs 中的队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com