How to cancel scheduled job with delayed_job in Rails?

后端 未结 4 1068
予麋鹿
予麋鹿 2020-12-07 17:49

I am scheduling a job to run in say, 10 minutes. How to properly cancel this particular job without using any kind of dirty extra fields in model and so on. Is there any cal

4条回答
  •  鱼传尺愫
    2020-12-07 18:30

    delayed_job 3 introduced a queue attribute. This can be hijacked to schedule a cancelable job.

    class MyJob < Struct.new(:user_id)
      def self.queue_name
        "something-unique"
      end
    
      def perform
        # ...
      end
    end
    
    #scheduler
    my_job = MyJob.new(User.first.id)
    #'cancel' pending jobs first
    Delayed::Job.where(queue: my_job.class.queue_name).destroy_all
    #queue it up
    Delayed::Job.enqueue(my_job,
      queue: my_job.class.queue_name,
      run_at: 1.hour.from_now
    )
    

提交回复
热议问题