SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PDF
Workshop 5: JavaScript testing
Visual Engineering
 
PDF
用 Go 語言打造多台機器 Scale 架構
Bo-Yi Wu
 
PDF
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
ODP
Puppet Node Classifiers Talk - Patrick Buckley
Christian Mague
 
PDF
Jeroen Vloothuis Bend Kss To Your Will
Vincenzo Barone
 
PPTX
Workshop 1: Good practices in JavaScript
Visual Engineering
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
andreaslubbe
 
PDF
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
PPT
Ruby on Rails Intro
zhang tao
 
PDF
ECMAScript 6
偉格 高
 
PPTX
ECMAScript 6 and the Node Driver
MongoDB
 
PPT
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Gosuke Miyashita
 
PDF
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
tdc-globalcode
 
PDF
Any event intro
qiang
 
PDF
Callbacks and control flow in Node js
Thomas Roch
 
PDF
clara-rules
Ikuru Kanuma
 
PDF
Flex With Rubyamf
Tony Hillerson
 
PDF
Swift Sequences & Collections
CocoaHeads France
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
Workshop 5: JavaScript testing
Visual Engineering
 
用 Go 語言打造多台機器 Scale 架構
Bo-Yi Wu
 
Introduction to asynchronous DB access using Node.js and MongoDB
Adrien Joly
 
Puppet Node Classifiers Talk - Patrick Buckley
Christian Mague
 
Jeroen Vloothuis Bend Kss To Your Will
Vincenzo Barone
 
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Avoiding Callback Hell with Async.js
cacois
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
andreaslubbe
 
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
Ruby on Rails Intro
zhang tao
 
ECMAScript 6
偉格 高
 
ECMAScript 6 and the Node Driver
MongoDB
 
Yapc::Asia 2008 Tokyo - Easy system administration programming with a framewo...
Gosuke Miyashita
 
TDC2018SP | Trilha Go - Processando analise genetica em background com Go
tdc-globalcode
 
Any event intro
qiang
 
Callbacks and control flow in Node js
Thomas Roch
 
clara-rules
Ikuru Kanuma
 
Flex With Rubyamf
Tony Hillerson
 
Swift Sequences & Collections
CocoaHeads France
 
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 

Similar to Background Jobs - Com BackgrounDRb (20)

PDF
Getting Distributed (With Ruby On Rails)
martinbtt
 
PDF
To Batch Or Not To Batch
Luca Mearelli
 
PPTX
Day 1 - Intro to Ruby
Barry Jones
 
PDF
Lessons Learnt in 2009
pratiknaik
 
PPTX
Exploring Ruby on Rails and PostgreSQL
Barry Jones
 
KEY
Foreman - Process manager for applications with multiple components
Stoyan Zhekov
 
PPTX
Grokking TechTalk #24: Thiết kế hệ thống Background Job Queue bằng Ruby & Pos...
Grokking VN
 
PDF
O que tem de novo no Ruby 2.0?
Fabio Akita
 
KEY
Wider than rails
Alexey Nayden
 
PDF
Complex Made Simple: Sleep Better with TorqueBox
bobmcwhirter
 
PDF
Release responsibly (Maintaining Backwards Compatibility)
Emily Stolfo
 
KEY
Lessons from Branch's launch
aflock
 
PDF
TorqueBox at DC:JBUG - November 2011
bobmcwhirter
 
KEY
Redis, Resque & Friends
Christopher Spring
 
KEY
TorqueBox - Ruby Hoedown 2011
Lance Ball
 
KEY
Freelancing and side-projects on Rails
John McCaffrey
 
PDF
Rocket Fuelled Cucumbers
Joseph Wilk
 
PDF
Lazy, Lazy, Lazy all the things !
Shaunak Pagnis
 
KEY
Rails performance at Justin.tv - Guillaume Luccisano
Guillaume Luccisano
 
KEY
Background Jobs with Resque
homanj
 
Getting Distributed (With Ruby On Rails)
martinbtt
 
To Batch Or Not To Batch
Luca Mearelli
 
Day 1 - Intro to Ruby
Barry Jones
 
Lessons Learnt in 2009
pratiknaik
 
Exploring Ruby on Rails and PostgreSQL
Barry Jones
 
Foreman - Process manager for applications with multiple components
Stoyan Zhekov
 
Grokking TechTalk #24: Thiết kế hệ thống Background Job Queue bằng Ruby & Pos...
Grokking VN
 
O que tem de novo no Ruby 2.0?
Fabio Akita
 
Wider than rails
Alexey Nayden
 
Complex Made Simple: Sleep Better with TorqueBox
bobmcwhirter
 
Release responsibly (Maintaining Backwards Compatibility)
Emily Stolfo
 
Lessons from Branch's launch
aflock
 
TorqueBox at DC:JBUG - November 2011
bobmcwhirter
 
Redis, Resque & Friends
Christopher Spring
 
TorqueBox - Ruby Hoedown 2011
Lance Ball
 
Freelancing and side-projects on Rails
John McCaffrey
 
Rocket Fuelled Cucumbers
Joseph Wilk
 
Lazy, Lazy, Lazy all the things !
Shaunak Pagnis
 
Rails performance at Justin.tv - Guillaume Luccisano
Guillaume Luccisano
 
Background Jobs with Resque
homanj
 
Ad

More from Juan Maiz (10)

PDF
Reasoning about Code with React
Juan Maiz
 
PDF
Code reviews
Juan Maiz
 
PDF
Ruby para-programadores-php
Juan Maiz
 
KEY
Ruby para-programadores-php
Juan Maiz
 
KEY
Ruby para programadores PHP
Juan Maiz
 
KEY
SaaS - RubyMastersConf.com.br
Juan Maiz
 
PDF
Saas
Juan Maiz
 
PDF
Tree top
Juan Maiz
 
PDF
Introdução ao Ruby on Rails
Juan Maiz
 
PPT
rails_and_agile
Juan Maiz
 
Reasoning about Code with React
Juan Maiz
 
Code reviews
Juan Maiz
 
Ruby para-programadores-php
Juan Maiz
 
Ruby para-programadores-php
Juan Maiz
 
Ruby para programadores PHP
Juan Maiz
 
SaaS - RubyMastersConf.com.br
Juan Maiz
 
Saas
Juan Maiz
 
Tree top
Juan Maiz
 
Introdução ao Ruby on Rails
Juan Maiz
 
rails_and_agile
Juan Maiz
 
Ad

Recently uploaded (20)

PDF
Per Axbom: The spectacular lies of maps
Nexer Digital
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
Per Axbom: The spectacular lies of maps
Nexer Digital
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 

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