ruby 如何根据数据库列每天运行sidekiq工作线程一定的次数?

t5zmwmid  于 2023-01-12  发布在  Ruby
关注(0)|答案(1)|浏览(97)

我的项目模型:

class Project < ApplicationRecord
  enum :number_of_samples, { once_per_day: 0, three_times_per_day: 1, hourly: 2 }, prefix: true
  
  belongs_to :project_owner, polymorphic: true
  has_many :metrics, dependent: :destroy
  has_one_attached :sitemap, dependent: :destroy

  validates :number_of_samples, presence: true
  validates :sitemap, presence: true, blob: { content_type: ['application/xml'], size_range: 1..(5.megabytes) }

  def attach_sitemap(sitemap_params)
    sitemap = ActiveStorage::Blob.create_and_upload!(
      io: sitemap_params[:io],
      filename: sitemap_params[:filename],
      content_type: sitemap_params[:content_type]
    )
    self.sitemap.attach(sitemap)
  end

  def sitemap_path
    ActiveStorage::Blob.service.path_for(sitemap.key)
  end
end

sidekiq工作者:

class PagespeedWorker
  include Sidekiq::Worker
  
  def perform
    puts 'Beginning Fetching...'
    projects = Project.all.order(created_at: :desc)
    projects.each do |project|
      sitemap_path = project.sitemap_path
      sitemap = SitemapParseService.call(sitemap_path)
      sitemap.each do |url|
        retrieve_data(url, 'desktop', project.id)
        retrieve_data(url, 'mobile', project.id)
      end
    end
    puts 'Fetching done!'
  end

  def retrieve_data(url, strategy, project_id)
    puts 'Pagespeed external call...'
    pagespeed_response = PagespeedService.call(url, strategy)
    puts 'Parsing Pagespeed response...'
    relevant_data = PagespeedParseService.call(pagespeed_response)
    puts 'Storing the relevant data...'
    PagespeedStore.call(relevant_data, strategy, url, project_id)
  end
end

每个项目都有一个上传的网站Map,上面有网站的所有网址。
对于每个URL,应该有2个外部API调用Pagespeed Insights,用于桌面和移动的。
我希望能够基于Project模型中的number_of_samples运行worker。
它应该为每个项目运行,为每个项目站点Map中的每个url运行,每天的次数在number_of_samples字段中指定。

eyh26e7m

eyh26e7m1#

可以使用number_of_samples属性循环
样本代码

projects.each do |project|
  project.number_of_samples.times do
    sitemap_path = project.sitemap_path
    sitemap = SitemapParseService.call(sitemap_path)
    sitemap.each do |url|
      retrieve_data(url, 'desktop', project.id)
      retrieve_data(url, 'mobile', project.id)
    end
  end
end

相关问题