SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
Background Jobs
       com BackgrounDRb

  da série "Palestras na Softa"
       blog.softa.com.br
Recomende: workingwithrails.com/person/9354
BackgrounDRb

BackgrounDRb é um agendador e servidor de tarefas em
Ruby.

Seu objetivo principal é ser utilizado com aplicações Ruby on
Rails - plugin - para desafogar tarefas de longa duração.

É feito com PACKET e não DRb. Mas pra entender o conceito,
vamos lá...
DRb

Isso é um "tipo" de digressão.
DRb é o Distributed Ruby.

Sim, um CORBA simplificado do Ruby.

Serialização de objetos sobre TCP.

DRb em Ruby é Standard Library.
http://ruby-doc.org/stdlib/libdoc/drb/rdoc/index.html
Hello DRb World

Clone:

git://github.com/softa/hello_drb_world.git
Simple (server)


require 'drb'
class TestServer
  def doit
    "Hello, Distributed World"
  end
end
server = TestServer.new
DRb.start_service('druby://localhost:9000', server)
DRb.thread.join
Simple (client)


require 'drb'
DRb.start_service()
obj = DRbObject.new(nil, 'druby://localhost:9000')
p obj.doit
Math (server)
require 'drb'
class MathServer
  attr_accessor :total
  def initialize(initial_value)
      @total = initial_value
  end
  def sum(value) @total += value; end
  def subtract(value) @total -= value; end
  def multiply(value) @total *= value; end
  def divide(value) @total /= value; end
end


DRb.start_service('druby://localhost:9000', MathServer.new(0))
DRb.thread.join
Math (client)
require 'drb'
DRb.start_service()
math = DRbObject.new(nil, 'druby://localhost:9000')
puts math.sum(10)
puts math.multiply(2)
puts math.subtract(5)
puts math.divide(3)
Math

$ ruby client.rb
10
20
15
5

$ ruby client.rb
15
30
25
8
Chat (server and client)

Open the files... please
Agora... BackgrounDRb

Fim da digressão.
Instalação do BackgrounDRb

GEMS necessárias:
sudo gem install chronic packet
Instalando:
script/plugin install git://github.com/gnufied/backgroundrb.git
sudo su postgres
createuser hello_backgroundrb_world
^d
rake db:create
rake backgroundrb:setup
(...gera migrações...)
rake db:migrate

 DONE!
Instalação do BackgrounDRb

Todo o código em:

http://github.com/softa/hello_backgroundrb_world
Iniciando do BackgrounDRb

script/backgroundrb start
script/backgroundrb start -e ENVIRONMENT
Config básico

config/backgroundrb.yml
---
:backgroundrb:
  :port: 11006
  :ip: 0.0.0.0
Conceitos-chave

 Server
 Um server que recebe as chamadas. Deve ser startado uma vez junto com o web
 server.
 MiddleMan
 Classe disponível (Factory) no Rails para chamar as tarefas dos workers em
 background, programar execuções ou busca informação sobre as tarefas.
 Worker
 É uma classes que define as tarefas possíveis de se utilizar. Cada worker inicia um
 processo próprio ao iniciar o server.
 Job
 É a execução de um método de um worker.
Conceitos-chave

 cache
 Hash com informações sobre a execução de um job.
 job_key
 Variável disponível no Worker para referenciar unicamente um Job.
 assync_*
 Executa o método * em background agora.
 enq_*
 Executa o método * em background no futuro.
Rake

rake -T backgroundrb
# Generate a migration for the backgroundrb queue table.
rake backgroundrb:queue_migration
# Drops and recreate backgroundrb queue table
rake backgroundrb:redo_queue
# Remove backgroundrb from your rails application
rake backgroundrb:remove
# Setup backgroundrb in your rails application
rake backgroundrb:setup
# update backgroundrb config files from your rails application
rake backgroundrb:update
# Generate documentation for the backgroundrb plugin
rake doc:plugins:backgroundrb
Gerador
script/generate worker WorkerName [options]
Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.
General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)
    -g, --git                        Modify files with git. (Note: git must be in path)

Description:
    The worker generator creates stubs for a new BackgrounDRb worker.

    The generator takes a worker name as its argument. The worker name may be
    given in CamelCase or under_score and should not be suffixed with 'Worker'.

    The generator creates a worker class in lib/workers and a test suite in
    test/unit.

Example:
    ./script/generate worker Tail

    This will create an Tail worker:
        Model:      lib/workers/tail_worker.rb
        Test:       test/unit/tail_worker_test.rb
Executar apenas um método
(com Ajax!)
script/generate worker Counter


         CounterController           CounterController
         :: start_counting           :: show_count


 MiddleMan                                       Ajax


        CounterWorker                CounterController
        :: start                     :: get_count

                             MiddleMan
Worker

class CounterWorker < BackgrounDRb::MetaWorker
  set_worker_name :counter_worker
  def create(args = nil)
  end
  def start
    cache[job_key] = 0
    add_periodic_timer(2) { increment }
  end
  def increment
    cache[job_key] += 1
    logger.warn "((#{cache[job_key]}))"
  end
end
Controller

script/generate controller Count start_counting show_count get_count
def start_counting
  t = Time.now.to_s
  session[:job_key] = t
  MiddleMan.worker(:counter_worker)
                .async_start(:job_key => t)
  redirect_to :action => :show_count
end
Controller

MiddleMan.worker(:counter_worker)
                .async_start(:job_key => t)
Controller

def show_count
end

# app/views/counter/show_count
<h1>Count#show_count</h1>
<div id="count"></div>
<script>
  new Ajax.PeriodicalRequest
('count','/counter/get_count')
</script>
Controller

def get_count
 return render :text =>
  MiddleMan.worker(:counter_worker).ask_result(session[:job_key])
end
Resultado
Executar um método no futuro

friend = Contact.find_by_name 'Rafael Lunardini'
MiddleMan.worker(:birthday_worker)
   .enq_send_congrats(:args => friend,
        :scheduled_at => friend.birthdate_in_this_year)

task = Task.find_by_name 'Reunião Unicórnio'
MiddleMan.worker(:task_worker)
   .enq_notice(:args => task,
        :scheduled_at => task.next_date)
Executar um método periodicamente

# config/backgroundrb.yml
---
:backgroundrb:
   :port: 11006
   :ip: 0.0.0.0
:schedules:
   :nightly_worker:
     :make_nightly_stuff:
        :trigger_args: 0 30 4 * * * *

Igual ao CRON, hum?
Executar um método periodicamente

Também rola isso:

:schedules:
:foo_worker:
:foobar:
:trigger_args:
:start: <%= Time.now + 5.seconds %>
:end: <%= Time.now + 10.minutes %>
:repeat_interval: <%= 1.minute %>
Advanced stuff

class ConnectorWorker < BackgrounDRb::MetaWorker
  set_worker_name :connector_worker
  def chat
    require 'drb'
    DRb.start_service()
    @chat = DRbObject.new(nil, 'druby://localhost:9000')
    @chat.login("Bot")
    add_periodic_timer(5) { talk }
  end
  def talk
    @chat.send_message("Bot", "i'm talking...")
  end
end
Advanced stuff
class TimeServer
def receive_data(p_data)
end
def post_init
add_periodic_timer(2) { say_hello_world }
end
def connection_completed
end
def say_hello_world
p "***************** : invoking hello world #{Time.now}"
send_data("Hello Worldn")
end
end
class ServerWorker < BackgrounDRb::MetaWorker
    set_worker_name :server_worker
    def create(args = nil)
      start_server("0.0.0.0",11009,TimeServer) do |client_connection|
        client_connection.say_hello_world
      end
    end
end

Weitere ähnliche Inhalte

Was ist angesagt?

Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBAdrien Joly
 
Puppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick BuckleyPuppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick BuckleyChristian Mague
 
Jeroen Vloothuis Bend Kss To Your Will
Jeroen Vloothuis   Bend Kss To Your WillJeroen Vloothuis   Bend Kss To Your Will
Jeroen Vloothuis Bend Kss To Your WillVincenzo Barone
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)xSawyer
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverMongoDB
 
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...Gosuke Miyashita
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Gotdc-globalcode
 
Any event intro
Any event introAny event intro
Any event introqiang
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)A K M Zahiduzzaman
 

Was ist angesagt? (20)

Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
 
Puppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick BuckleyPuppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick Buckley
 
Jeroen Vloothuis Bend Kss To Your Will
Jeroen Vloothuis   Bend Kss To Your WillJeroen Vloothuis   Bend Kss To Your Will
Jeroen Vloothuis Bend Kss To Your Will
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node Driver
 
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com GoTDC2018SP | Trilha Go - Processando analise genetica em background com Go
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
 
Any event intro
Any event introAny event intro
Any event intro
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
clara-rules
clara-rulesclara-rules
clara-rules
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)
 

Ähnlich wie Background Jobs - Com BackgrounDRb

Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomMore on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomValeriy Kravchuk
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Masahiro Nagano
 
Debugging on Rails. Mykhaylo Sorochan
Debugging on Rails. Mykhaylo SorochanDebugging on Rails. Mykhaylo Sorochan
Debugging on Rails. Mykhaylo SorochanSphere Consulting Inc
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworksdiego_k
 
Curscatalyst
CurscatalystCurscatalyst
CurscatalystKar Juan
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonManageIQ
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceJesse Vincent
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Getting Started with Capistrano
Getting Started with CapistranoGetting Started with Capistrano
Getting Started with CapistranoLaunchAny
 

Ähnlich wie Background Jobs - Com BackgrounDRb (20)

Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB DevroomMore on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
More on bpftrace for MariaDB DBAs and Developers - FOSDEM 2022 MariaDB Devroom
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Debugging on rails
Debugging on railsDebugging on rails
Debugging on rails
 
Debugging on Rails. Mykhaylo Sorochan
Debugging on Rails. Mykhaylo SorochanDebugging on Rails. Mykhaylo Sorochan
Debugging on Rails. Mykhaylo Sorochan
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Laravel tips-2019-04
Laravel tips-2019-04Laravel tips-2019-04
Laravel tips-2019-04
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Curscatalyst
CurscatalystCurscatalyst
Curscatalyst
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron Patterson
 
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret SauceBeijing Perl Workshop 2008 Hiveminder Secret Sauce
Beijing Perl Workshop 2008 Hiveminder Secret Sauce
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Getting Started with Capistrano
Getting Started with CapistranoGetting Started with Capistrano
Getting Started with Capistrano
 

Mehr von Juan Maiz

Reasoning about Code with React
Reasoning about Code with ReactReasoning about Code with React
Reasoning about Code with ReactJuan Maiz
 
Code reviews
Code reviewsCode reviews
Code reviewsJuan Maiz
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
Ruby para programadores PHP
Ruby para programadores PHPRuby para programadores PHP
Ruby para programadores PHPJuan Maiz
 
SaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brSaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brJuan Maiz
 
Introdução ao Ruby on Rails
Introdução ao Ruby on RailsIntrodução ao Ruby on Rails
Introdução ao Ruby on RailsJuan Maiz
 
rails_and_agile
rails_and_agilerails_and_agile
rails_and_agileJuan Maiz
 

Mehr von Juan Maiz (10)

Reasoning about Code with React
Reasoning about Code with ReactReasoning about Code with React
Reasoning about Code with React
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
Ruby para programadores PHP
Ruby para programadores PHPRuby para programadores PHP
Ruby para programadores PHP
 
SaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brSaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.br
 
Saas
SaasSaas
Saas
 
Tree top
Tree topTree top
Tree top
 
Introdução ao Ruby on Rails
Introdução ao Ruby on RailsIntrodução ao Ruby on Rails
Introdução ao Ruby on Rails
 
rails_and_agile
rails_and_agilerails_and_agile
rails_and_agile
 

Kürzlich hochgeladen

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 

Background Jobs - Com BackgrounDRb

  • 1. Background Jobs com BackgrounDRb da série "Palestras na Softa" blog.softa.com.br Recomende: workingwithrails.com/person/9354
  • 2. BackgrounDRb BackgrounDRb é um agendador e servidor de tarefas em Ruby. Seu objetivo principal é ser utilizado com aplicações Ruby on Rails - plugin - para desafogar tarefas de longa duração. É feito com PACKET e não DRb. Mas pra entender o conceito, vamos lá...
  • 3. DRb Isso é um "tipo" de digressão. DRb é o Distributed Ruby. Sim, um CORBA simplificado do Ruby. Serialização de objetos sobre TCP. DRb em Ruby é Standard Library. http://ruby-doc.org/stdlib/libdoc/drb/rdoc/index.html
  • 5. Simple (server) require 'drb' class TestServer def doit "Hello, Distributed World" end end server = TestServer.new DRb.start_service('druby://localhost:9000', server) DRb.thread.join
  • 6. Simple (client) require 'drb' DRb.start_service() obj = DRbObject.new(nil, 'druby://localhost:9000') p obj.doit
  • 7. Math (server) require 'drb' class MathServer attr_accessor :total def initialize(initial_value) @total = initial_value end def sum(value) @total += value; end def subtract(value) @total -= value; end def multiply(value) @total *= value; end def divide(value) @total /= value; end end DRb.start_service('druby://localhost:9000', MathServer.new(0)) DRb.thread.join
  • 8. Math (client) require 'drb' DRb.start_service() math = DRbObject.new(nil, 'druby://localhost:9000') puts math.sum(10) puts math.multiply(2) puts math.subtract(5) puts math.divide(3)
  • 9. Math $ ruby client.rb 10 20 15 5 $ ruby client.rb 15 30 25 8
  • 10. Chat (server and client) Open the files... please
  • 12. Instalação do BackgrounDRb GEMS necessárias: sudo gem install chronic packet Instalando: script/plugin install git://github.com/gnufied/backgroundrb.git sudo su postgres createuser hello_backgroundrb_world ^d rake db:create rake backgroundrb:setup (...gera migrações...) rake db:migrate DONE!
  • 13. Instalação do BackgrounDRb Todo o código em: http://github.com/softa/hello_backgroundrb_world
  • 14. Iniciando do BackgrounDRb script/backgroundrb start script/backgroundrb start -e ENVIRONMENT
  • 16. Conceitos-chave Server Um server que recebe as chamadas. Deve ser startado uma vez junto com o web server. MiddleMan Classe disponível (Factory) no Rails para chamar as tarefas dos workers em background, programar execuções ou busca informação sobre as tarefas. Worker É uma classes que define as tarefas possíveis de se utilizar. Cada worker inicia um processo próprio ao iniciar o server. Job É a execução de um método de um worker.
  • 17. Conceitos-chave cache Hash com informações sobre a execução de um job. job_key Variável disponível no Worker para referenciar unicamente um Job. assync_* Executa o método * em background agora. enq_* Executa o método * em background no futuro.
  • 18. Rake rake -T backgroundrb # Generate a migration for the backgroundrb queue table. rake backgroundrb:queue_migration # Drops and recreate backgroundrb queue table rake backgroundrb:redo_queue # Remove backgroundrb from your rails application rake backgroundrb:remove # Setup backgroundrb in your rails application rake backgroundrb:setup # update backgroundrb config files from your rails application rake backgroundrb:update # Generate documentation for the backgroundrb plugin rake doc:plugins:backgroundrb
  • 19. Gerador script/generate worker WorkerName [options] Rails Info: -v, --version Show the Rails version number and quit. -h, --help Show this help message and quit. General Options: -p, --pretend Run but do not make any changes. -f, --force Overwrite files that already exist. -s, --skip Skip files that already exist. -q, --quiet Suppress normal output. -t, --backtrace Debugging: show backtrace on errors. -c, --svn Modify files with subversion. (Note: svn must be in path) -g, --git Modify files with git. (Note: git must be in path) Description: The worker generator creates stubs for a new BackgrounDRb worker. The generator takes a worker name as its argument. The worker name may be given in CamelCase or under_score and should not be suffixed with 'Worker'. The generator creates a worker class in lib/workers and a test suite in test/unit. Example: ./script/generate worker Tail This will create an Tail worker: Model: lib/workers/tail_worker.rb Test: test/unit/tail_worker_test.rb
  • 20. Executar apenas um método (com Ajax!) script/generate worker Counter CounterController CounterController :: start_counting :: show_count MiddleMan Ajax CounterWorker CounterController :: start :: get_count MiddleMan
  • 21. Worker class CounterWorker < BackgrounDRb::MetaWorker set_worker_name :counter_worker def create(args = nil) end def start cache[job_key] = 0 add_periodic_timer(2) { increment } end def increment cache[job_key] += 1 logger.warn "((#{cache[job_key]}))" end end
  • 22. Controller script/generate controller Count start_counting show_count get_count def start_counting t = Time.now.to_s session[:job_key] = t MiddleMan.worker(:counter_worker) .async_start(:job_key => t) redirect_to :action => :show_count end
  • 23. Controller MiddleMan.worker(:counter_worker) .async_start(:job_key => t)
  • 24. Controller def show_count end # app/views/counter/show_count <h1>Count#show_count</h1> <div id="count"></div> <script> new Ajax.PeriodicalRequest ('count','/counter/get_count') </script>
  • 25. Controller def get_count return render :text => MiddleMan.worker(:counter_worker).ask_result(session[:job_key]) end
  • 27. Executar um método no futuro friend = Contact.find_by_name 'Rafael Lunardini' MiddleMan.worker(:birthday_worker) .enq_send_congrats(:args => friend, :scheduled_at => friend.birthdate_in_this_year) task = Task.find_by_name 'Reunião Unicórnio' MiddleMan.worker(:task_worker) .enq_notice(:args => task, :scheduled_at => task.next_date)
  • 28. Executar um método periodicamente # config/backgroundrb.yml --- :backgroundrb: :port: 11006 :ip: 0.0.0.0 :schedules: :nightly_worker: :make_nightly_stuff: :trigger_args: 0 30 4 * * * * Igual ao CRON, hum?
  • 29. Executar um método periodicamente Também rola isso: :schedules: :foo_worker: :foobar: :trigger_args: :start: <%= Time.now + 5.seconds %> :end: <%= Time.now + 10.minutes %> :repeat_interval: <%= 1.minute %>
  • 30. Advanced stuff class ConnectorWorker < BackgrounDRb::MetaWorker set_worker_name :connector_worker def chat require 'drb' DRb.start_service() @chat = DRbObject.new(nil, 'druby://localhost:9000') @chat.login("Bot") add_periodic_timer(5) { talk } end def talk @chat.send_message("Bot", "i'm talking...") end end
  • 31. Advanced stuff class TimeServer def receive_data(p_data) end def post_init add_periodic_timer(2) { say_hello_world } end def connection_completed end def say_hello_world p "***************** : invoking hello world #{Time.now}" send_data("Hello Worldn") end end class ServerWorker < BackgrounDRb::MetaWorker set_worker_name :server_worker def create(args = nil) start_server("0.0.0.0",11009,TimeServer) do |client_connection| client_connection.say_hello_world end end end