轨道:创建对象 10 分钟后删除对象



如何在对象created后的某些时间delete对象?

我以为会是这样的?但是,如何安排此操作呢?

  after_create :destroy_essay
  def destroy_essay
    #  10minutes later
    # self.destroy  
  end

对于后台工作者来说,这实际上是一项完美的工作。我绝对建议使用 Sidekiq 它甚至提供了一种在未来一定时间后执行工作的方法。https://github.com/mperham/sidekiq/wiki/Scheduled-Jobs

EssayDestroyer.perform_at(10.minutes.from_now)

然后,在您的EssayDestroyer工作者上编写要执行的代码以销毁您创建的文章。

您可能应该为此编写 rake 任务,并使用 cron,或者如果您在 Heroku 上,则使用 Heroku 调度程序来运行它。

在模型中添加一个范围,例如 expired ,它返回所有超过 10 分钟的项目,然后在 rake 任务中执行Essay.expired.destroy_all并运行此任务,例如每 1 分钟一次。

这个耙子可以看起来像这样:

namespace :app do
  desc "Remove expired essays"
  task :remove_expired_essays => :environment do
    Essay.expired.destroy_all
  end
end

以及模型中的范围:

scope :expired, -> { where('created_at >= ?', 10.minutes.ago) }

@methyl我认为正确的范围是scope :expired, -> { where('created_at <= ?', 10.minutes.ago) },不是吗?

最新更新