美文网首页Ruby On Rails
rails中的ActiveJob和sidekiq

rails中的ActiveJob和sidekiq

作者: kamionayuki | 来源:发表于2015-07-01 21:17 被阅读1231次
    • 首先要先安装redis服务器端
    sudo apt-get install redis-server
    
    # 检查Redis服务器系统进程
    ~ ps -aux|grep redis
    redis     4162  0.1  0.0  10676  1420 ?        Ss   23:24   0:00 /usr/bin/redis-server /etc/redis/redis.conf
    conan     4172  0.0  0.0  11064   924 pts/0    S+   23:26   0:00 grep --color=auto redis
    
    # 通过启动命令检查Redis服务器状态
    ~ netstat -nlt|grep 6379
    tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN
    
    # 通过启动命令检查Redis服务器状态
    ~ sudo /etc/init.d/redis-server status
    redis-server is running
    
    • 安装好redis后,就可以安装sidekiq了
    gem 'sidekiq'
    

    配置Active Job adapter

    class Application < Rails::Application
      # ...
      config.active_job.queue_adapter = :sidekiq
    end
    
    • 运行sidkiq
      在app的根目录下
    bundle exec sidekiq
    
    • 一切准备好后,就可以用ActiveRecord Job
    rails g job Prac
    #invoke  test_unit
    #create    test/jobs/prac_job_test.rb
    #create  app/jobs/prac_job.rb
    

    prac_job.rb

    class PracJob < ActiveJob::Base
      queue_as :default
    
      def perform(string)
        #do something in there
        #order = Order.first
        #order.user_name = string
        #order.save
      end
    end
    
    • modelcontroller中调用job
    # PracJob.perform_later("prac001")马上运行job
    # PracJob.set(wait: 30.second).perform_later("prac002")30秒后运行job
    # PracJob.set(wait_until: Time.new(2015,7,1,20,45,00)).perform_later("prac003")直到2015-7-1 20:45:00运行job
    

    相关文章

      网友评论

        本文标题:rails中的ActiveJob和sidekiq

        本文链接:https://www.haomeiwen.com/subject/kmxyqttx.html