Ruby on rails学习:cms里的文章定时发布功能实现-rescue

利用rescue-schedule实现定时的任务,原理是利用 redis的key过期通知机制
更新于: 2022-03-19 06:57:20

准备工作

  • 安装 redis-server
  • 添加相关的gem
gem 'resque'
gem 'resque-scheduler'

rails 里配置 redis

  • touch config/initializers/redis.rb
  • 写入配置文件如下
  • 这里的密码写: 123456
host = Rails.env.production? ? '201.112.12.1' : 'localhost'
Resque.redis = "redis://default:123456@#{host}:6379"

新建一个config/resque_schedule.yml

特别留意,args暂时得保留(publish其实没有用到)

posts_publish:
  every: 30s
  class: PostJob
  args:
    - publish
  queue: scheduled
  description: Runs the perform method in PostJob every 30 seconds

新建一个resque.rake

目标位置: lib/tasks/resque.rake

# Resque tasks
require 'resque/tasks'
require 'resque/scheduler/tasks'

namespace :resque do
  task :setup do
    require 'resque'

    # you probably already have this somewhere
    # Resque.redis = 'localhost:6379'
    ENV['QUEUE'] = '*'
  end

  task :setup_schedule => :setup do
    require 'resque-scheduler'
    Resque.schedule = YAML.load_file("#{Rails.root}/config/resque_schedule.yml")
  end

  task :scheduler => :setup_schedule
end

新建 post_job.rb

目标位置在这里: app/jobs/post_job.rb

class PostJob
  @queue = :scheduled

  def self.perform
    Post.publish!
  end
end

如果想查看web界面

routes.rb 里添加下面内容,查看 http://localhost:3000/resque/overview

require 'resque/scheduler'
require 'resque/scheduler/server'

Rails.application.routes.draw do
  mount Resque::Server.new, at: "/resque"
  # ....
end

启动项目

  • 启动 rails 服务
  • 启动 resque-schedule 相关的 task
rails s 
rake environment resque:scheduler

如果无法实现,看这个 error

DM查看一报错信息 : wrong number of arguments (given 0, expected 1)

{
  "failed_at": "2022/03/19 14:14:36 CST",
  "payload": {
    "class": "PostJob",
    "args": [

    ]
  },
  "exception": "ArgumentError",
  "error": "wrong number of arguments (given 0, expected 1)",
  "backtrace": [
    "your_project/app/jobs/post_job.rb:4:in `perform'"
  ],
  "worker": "ariczheng.local:76219:*",
  "queue": "scheduled"
}

总结

  1. 这个方法,相对于 crontab(whenever) 的思路较为复杂
  2. 性能方面不确定

参考