How can I schedule a 'weekly' job on Heroku?

前端 未结 5 1798
走了就别回头了
走了就别回头了 2020-12-24 08:49

I have a Rails app deployed on Heroku with the Heroku scheduler add-on successfully working for daily jobs.

Now I want a weekly job, but the schedul

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 08:57

    It's not ideal, but I've taken to adding a RUN_IF environment variable to rake tasks run through heroku:scheduler which lets me weekly and monthly schedules for jobs.

    # lib/tasks/scheduler.rake
    def run?
      eval ENV.fetch('RUN_IF', 'true')
    end
    
    def scheduled
      if run?
        yield
      else
        puts "RUN_IF #{ENV['RUN_IF'].inspect} eval'd to false: aborting job."
      end
    end
    
    # lib/tasks/job.rake
    task :job do
      scheduled do
        # ...
      end
    end
    

    If a rake task is run without a RUN_IF variable it will run. Otherwise, the job will be aborted unless the value of RUN_IF evals to a falsey value.

    $ rake job                              # => runs always
    $ rake job RUN_IF='Date.today.monday?'  # => only runs on Mondays
    $ rake job RUN_IF='Date.today.day == 1' # => only runs on the 1st of the month
    $ rake job RUN_IF='false'               # => never runs (not practical, just demonstration)
    

    Similar to other ideas above, but I prefer moving the scheduling details out of the application code.

提交回复
热议问题