A presentation with tips and tools on how to integrate batch and asynchronous operations in a generic ruby on rails application.
Did this at rubyday.it 2011
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
A wise hacker said: Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Regular expressions are a powerful tool in our hands and a first class citizen in ruby so it is tempting to overuse them. But knowing them and using them properly is a fundamental asset of every developer.
We’ll see hands-on examples of proper Reg Exps usage in ruby code, we’ll also look at bad and ugly cases and learn how to approach writing, testing and debugging regular expressions.
OSCON Google App Engine Codelab - July 2010ikailan
Slides for the App Engine codelab given on July 20, 2010. Note that a more verbose version of this codelab is available at:
https://sites.google.com/site/gdevelopercodelabs/app-engine/python-codelab
We start with why you should use task queues. Then we show a few straightforward examples with Python and Celery and Ruby and Resque.
Finally, we wrap up with a quick example of a task queue in PHP using Redis.
https://github.com/bryanhelmig/phqueue
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
A wise hacker said: Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Regular expressions are a powerful tool in our hands and a first class citizen in ruby so it is tempting to overuse them. But knowing them and using them properly is a fundamental asset of every developer.
We’ll see hands-on examples of proper Reg Exps usage in ruby code, we’ll also look at bad and ugly cases and learn how to approach writing, testing and debugging regular expressions.
OSCON Google App Engine Codelab - July 2010ikailan
Slides for the App Engine codelab given on July 20, 2010. Note that a more verbose version of this codelab is available at:
https://sites.google.com/site/gdevelopercodelabs/app-engine/python-codelab
We start with why you should use task queues. Then we show a few straightforward examples with Python and Celery and Ruby and Resque.
Finally, we wrap up with a quick example of a task queue in PHP using Redis.
https://github.com/bryanhelmig/phqueue
Learn the ins and outs of running background tasks with the popular python module Celery. We'll hit the ground running. With everything you need to know to run your first task, to scaling your stack to run millions each day.
Video presentation: https://www.youtube.com/watch?v=jLAFXQ1Av50
Most applications written in Ruby are great, but also exists evil code applying WOP techniques. There are many workarounds in several programming languages, but in Ruby, when it happens, the proportion is bigger. It's very easy to write Ruby code with collateral damage.
You will see a collection of bad Ruby codes, with a description of how these codes affected negatively their applications and the solutions to fix and avoid them. Long classes, coupling, misapplication of OO, illegible code, tangled flows, naming issues and other things you can ever imagine are examples what you'll get.
New Symfony Tips & Tricks (SymfonyCon Paris 2015)Javier Eguiluz
This talk included tens of tips and tricks, new features and rarely used options for Symfony and its ecosystem. Besides the full-stack Symfony framework, other related technologies were mentioned, like Doctrine, Composer, Twig, PHPUnit and Monolog.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017Ryan Weaver
What is Symfony *really*? It's a collection of *35* independent libraries, and
Drupal uses less than *half* of them! That means that there's a *ton* of other
good stuff that you can bring into your project to solve common problems... as
long as you know how, and what those components do!
In this talk, we'll have some fun: taking a tour of the Symfony components, how
to install them (into Drupal, or anywhere) and how to use some of my *favorite*,
lesser-known components. By the end, you'll have a better appreciation of what
Symfony *really* is, and some new tools to use immediately.
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
These are the slides of the code-centered presentation I did with Giorgio Cefaro at the Javascript UserGroup Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
A year ago, I was a committed VPS and dedicated-machine deployer. I thought the cloud imposed silly restrictions - how dare you take away my shell account! Whaddya mean I can't save files locally? Since then, I've had some interesting experiences. I've worked on big cloud-deployed systems, and certain large traditionally-deployed systems, and I've seen how a lot of the decisions that you're ... encouraged to make when designing an app to run in the cloud. Most interestingly, I've discovered how those same decisions can make for a much better app regardless of where it'll end up. In this talk, I'll share those architectural patterns with you, and show why they work. Hopefully, I'll convince all of you to build cloud castles -- even if you've got your foundation firmly on the ground.
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Ville Mattila
Slides of my half an hour talk at Symfony Sweden November Camp, held at Hilton Slussen on Friday 22nd Nov 2013. Slides contain a generic infrastructure overview of running Eventio.com on Amazon Web Services and show a few details to consider when designing and running a distributed, reliable and scalable PHP application.
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
Slides contain RESTful solutions based on Python frameworks like Flask and Django. The presentation introduce in REST concept, presents benchmarks and research for best solutions, analyzes performance problems and shows how to simple get better results. Finally presents soruce code in Flask and Django how to make your own RESTful API in 15 minutes.
"The road to Ember.js 2.0" by Lucio Grenzi
Why should I use Ember.js? JavaScript MVC frameworks are plentiful. In this presentation I will give you some compelling reasons to consider Ember,and the the new parts coming from the upcoming version 2.0. Different from other framework the new vesion does not brings a far new world because the dev team has planned continuos releases in order to improve backward compatibility. But there are new parts, like in React, the "virtual DOM" to improve performance. In this talk I will go through the new parts of EmberJS 2.0
Effective Doctrine2: Performance Tips for Symfony2 DevelopersMarcin Chwedziak
How to boost performance Doctrine2 with Symfony2. How to configure metadata caching? How to optimize DQL queries for caching. How to properly setup transaction demarcation with EntityManager. How to deal with EntityManager and Listeners with Symfony2 container.
Learn the ins and outs of running background tasks with the popular python module Celery. We'll hit the ground running. With everything you need to know to run your first task, to scaling your stack to run millions each day.
Video presentation: https://www.youtube.com/watch?v=jLAFXQ1Av50
Most applications written in Ruby are great, but also exists evil code applying WOP techniques. There are many workarounds in several programming languages, but in Ruby, when it happens, the proportion is bigger. It's very easy to write Ruby code with collateral damage.
You will see a collection of bad Ruby codes, with a description of how these codes affected negatively their applications and the solutions to fix and avoid them. Long classes, coupling, misapplication of OO, illegible code, tangled flows, naming issues and other things you can ever imagine are examples what you'll get.
New Symfony Tips & Tricks (SymfonyCon Paris 2015)Javier Eguiluz
This talk included tens of tips and tricks, new features and rarely used options for Symfony and its ecosystem. Besides the full-stack Symfony framework, other related technologies were mentioned, like Doctrine, Composer, Twig, PHPUnit and Monolog.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017Ryan Weaver
What is Symfony *really*? It's a collection of *35* independent libraries, and
Drupal uses less than *half* of them! That means that there's a *ton* of other
good stuff that you can bring into your project to solve common problems... as
long as you know how, and what those components do!
In this talk, we'll have some fun: taking a tour of the Symfony components, how
to install them (into Drupal, or anywhere) and how to use some of my *favorite*,
lesser-known components. By the end, you'll have a better appreciation of what
Symfony *really* is, and some new tools to use immediately.
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
These are the slides of the code-centered presentation I did with Giorgio Cefaro at the Javascript UserGroup Roma and the PHP User Group Roma.
In this presentation we try to show many powerful features of symfony2 and its bundles to work as a backend system for single page applications.
On the client side we describe how we made a javascript editable grid using Backbone.js and its plugin for grids Backgrid.js.
A year ago, I was a committed VPS and dedicated-machine deployer. I thought the cloud imposed silly restrictions - how dare you take away my shell account! Whaddya mean I can't save files locally? Since then, I've had some interesting experiences. I've worked on big cloud-deployed systems, and certain large traditionally-deployed systems, and I've seen how a lot of the decisions that you're ... encouraged to make when designing an app to run in the cloud. Most interestingly, I've discovered how those same decisions can make for a much better app regardless of where it'll end up. In this talk, I'll share those architectural patterns with you, and show why they work. Hopefully, I'll convince all of you to build cloud castles -- even if you've got your foundation firmly on the ground.
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Ville Mattila
Slides of my half an hour talk at Symfony Sweden November Camp, held at Hilton Slussen on Friday 22nd Nov 2013. Slides contain a generic infrastructure overview of running Eventio.com on Amazon Web Services and show a few details to consider when designing and running a distributed, reliable and scalable PHP application.
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
Slides contain RESTful solutions based on Python frameworks like Flask and Django. The presentation introduce in REST concept, presents benchmarks and research for best solutions, analyzes performance problems and shows how to simple get better results. Finally presents soruce code in Flask and Django how to make your own RESTful API in 15 minutes.
"The road to Ember.js 2.0" by Lucio Grenzi
Why should I use Ember.js? JavaScript MVC frameworks are plentiful. In this presentation I will give you some compelling reasons to consider Ember,and the the new parts coming from the upcoming version 2.0. Different from other framework the new vesion does not brings a far new world because the dev team has planned continuos releases in order to improve backward compatibility. But there are new parts, like in React, the "virtual DOM" to improve performance. In this talk I will go through the new parts of EmberJS 2.0
Effective Doctrine2: Performance Tips for Symfony2 DevelopersMarcin Chwedziak
How to boost performance Doctrine2 with Symfony2. How to configure metadata caching? How to optimize DQL queries for caching. How to properly setup transaction demarcation with EntityManager. How to deal with EntityManager and Listeners with Symfony2 container.
As more and more web applications integrate with third-party APIs and other external data, processing those external resources in the background more and more important. A simple job runner is a great start, however as your load increases, you very quickly outgrew that simplistic queuing system. We will cover where getting started using Resque and Redis, how to test your jobs, when it makes sense to use Resque, implementations of Resque in other languages, and look how I've used Resque.
A wise hacker said: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Regular expressions are a powerful tool in our hands and a first class citizen in ruby so it is tempting to overuse them. But knowing them and using them properly is a fundamental asset of every developer. We'll see hands-on examples of proper Reg Exps usage in ruby code, we'll look at bad and ugly cases, and learn how to approach writing and debugging them.
We have a lot of data at our disposal, and we are ever more producing and collecting data from multiple sources. Data visualizations let us turn raw data into relevant information and make it easier to extract meaning from the information and to reason about it.
This talk will show you visualizations of increasing complexity all developed with d3js and we’ll analyze how they are built.
Molta attenzione e molti sforzi vengono spesi nello sviluppo delle parti 'visibili' dei servizi online (per ovvie ragioni) mentre al retrobottega si dedica il minimo investimento necessario.
Il risultato è spesso un sistema sgangherato che non permette di effettuare le operazioni essenziali per la gestione del sito o le rende oltremodo complicate e questo si riflette in modo negativo sugli utenti del servizio:
- diventa difficile rispondere con rapidità e positivamente alle richieste degli utenti,
- non ci si accorge che l'applicazione ha dei problemi,
- non si riescono ad implementare differenti approcci commerciali e a testarne i risultati,
La soluzione è cercare di prestare maggiore attenzione alla creazione del sistema che utilizzeremo per controllare e gestire il nostro servizio web, considerando il backoffice un elemento essenziale dell'applicazione che realizziamo, e fecendo in modo che ne segua l'evoluzione.
La creazione di software è un'attività complessa. Decine di presentazioni in questa conferenza mostreranno di come migliorare il processo di sviluppo del software per realizzare prodotti e servizi in maniera più efficiente ed agile, usando meno risorse e meno capitali per ottenere servizi di maggiore qualità.
Questa NON è una di quelle presentazioni.
Quello che faremo è un (piccolo) viaggio nel tunnel degli orrori dello sviluppo e della gestione di progetti software, raccontando di anti-pattern che possono essere deleteri anche per il migliore dei team e far fallire anche la migliore delle idee.
Vedremo come azioni spesso insignificanti possano peggiorare il processo di sviluppo rendendolo meno efficiente, più costoso e più rigido, ottenendo prodotti complessi, difficili da utilizzare e meno utili.
Dunque se la creazione di software è un'attività complessa, più di quanto a volte possiamo rendercene conto, una delle prime regole per migliorare è quella di riconoscere gli errori che si compiono, condividerli ed imparare da essi.
Questo ci farà guardare con occhi diversi alle "best practice" aiutandoci a scegliere la cura migliore per gli anti-pattern che incontreremo.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
"Impact of front-end architecture on development cost", Viktor Turskyi
To Batch Or Not To Batch
1. To Batch Or Not To Batch
Luca Mearelli
rubyday.it 2011
2. First and foremost, we believe that speed
is more than a feature. Speed is the most
important feature. If your application is
application is
slow, people won’t use it.
people won’t use it.
Fred Wilson
@lmea #rubyday
3. Not all the interesting features are fast
Interacting with remote API
Sending emails
Media transcoding
Large dataset handling
@lmea #rubyday
4. Anatomy of an asynchronous action
The app decides it needs to do a long operation
The app asks the async system to do the
operation and quickly returns the response
The async system executes the operation out-
of-band
@lmea #rubyday
7. Cron
scheduled operations
unrelated to the requests
low frequency
longer run time
@lmea #rubyday
8. Anatomy of a cron batch: the rake task
namespace :export do
task :items_xml => :environment do
# read the env variables
# make the export
end
end
@lmea #rubyday
9. Anatomy of a cron batch: the shell script
#!/bin/sh
# this goes in script/item_export_full.sh
cd /usr/rails/MyApp/current
export RAILS_ENV=production
echo "Item Export Full started: `date`"
rake export:items_xml XML_FOLDER='data/exports'
echo "Item Export Full completed: `date`"
@lmea #rubyday
10. Anatomy of a cron batch: the crontab entry
0 0 1 * * /usr/rails/MyApp/current/script/item_export_full.sh >> /usr/rails/
MyApp/current/log/dump_item_export.log 2>&1
30 13 * * * cd /usr/rails/MyApp/current; ruby /usr/rails/MyApp/current/script/
runner -e production "Newsletter.deliver_daily" >> /usr/rails/MyApp/current/log/
newsletter_daily.log 2>&1
@lmea #rubyday
12. Whenever: schedule.rb
# adds ">> /path/to/file.log 2>&1" to all commands
set :output, '/path/to/file.log'
every 3.hours do
rake "my:rake:task"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
command "/usr/bin/my_great_command", :output => {:error =>
'error.log', :standard => 'cron.log'}
end
@lmea #rubyday
17. Delayed job
Any object method can be a job
Db backed queue
Integer-based priority
Lifecycle hooks (enqueue, before, after, ... )
@lmea #rubyday
18. Delayed job: simple jobs
# without delayed_job
@user.notify!(@event)
# with delayed_job
@user.delay.notify!(@event)
# always asyncronous method
class Newsletter
def deliver
# long running method
end
handle_asynchronously :deliver
end
newsletter = Newsletter.new
newsletter.deliver
@lmea #rubyday
22. Delayed job: checking the job status
The queue is for scheduled and running jobs
Handle the status outside Delayed::Job object
@lmea #rubyday
23. Delayed job: checking the job status
# Include this in your initializers somewhere
class Queue < Delayed::Job
def self.status(id)
self.find_by_id(id).nil? ? "success" : (job.last_error.nil? ? "queued" : "failure")
end
end
# Use this method in your poll method like so:
def poll
status = Queue.status(params[:id])
if status == "success"
# Success, notify the user!
elsif status == "failure"
# Failure, notify the user!
end
end
@lmea #rubyday
24. Delayed job: checking the job status
class AJob < Struct.new(:options)
def perform
do_something(options)
end
def success(job)
# record success of job.id
Rails.cache.write("status:#{job.id}", "success")
end
end
# a helper
def job_completed_with_success(job_id)
Rails.cache.read("status:#{job_id}")=="success"
end
@lmea #rubyday
25. Resque
Redis-backed queues
Queue/dequeue speed independent of list size
Forking behaviour
Built in front-end
Multiple queues / no priorities
@lmea #rubyday
26. Resque: the job
class Export
@queue = :export_jobs
def self.perform(dataset_id, kind = 'full')
ds = Dataset.find(dataset_id)
ds.create_export(kind)
end
end
@lmea #rubyday
27. Resque: enqueuing the job
class Dataset
def async_create_export(kind)
Resque.enqueue(Export, self.id, kind)
end
end
ds = Dataset.find(100)
ds.async_create_export('full')
@lmea #rubyday
28. Resque: persisting the job
# jobs are persisted as JSON,
# so jobs should only take arguments that can be expressed as JSON
{
'class': 'Export',
'args': [ 100, 'full' ]
}
# don't do this: Resque.enqueue(Export, self, kind)
# do this:
Resque.enqueue(Export, self.id, kind)
@lmea #rubyday
29. Resque: generic async methods
# A simple async helper
class Repository < ActiveRecord::Base
# This will be called by a worker when a job needs to be processed
def self.perform(id, method, *args)
find(id).send(method, *args)
end
# We can pass this any Repository instance method that we want to
# run later.
def async(method, *args)
Resque.enqueue(Repository, id, method, *args)
end
end
# Now we can call any method and have it execute later:
@repo.async(:update_disk_usage)
@repo.async(:update_network_source_id, 34)
@lmea #rubyday
30. Resque: anatomy of a worker
# a worker does this:
start
loop do
if job = reserve
job.process
else
sleep 5
end
end
shutdown
@lmea #rubyday
31. Resque: working the queues
$ QUEUES=critical,high,low rake resque:work
$ QUEUES=* rake resque:work
$ PIDFILE=./resque.pid QUEUE=export_jobs rake environment resque:work
task "resque:setup" => :environment do
AppConfig.a_parameter = ...
end
@lmea #rubyday
32. Resque: monit recipe
# example monit monitoring recipe
check process resque_worker_batch_01
with pidfile /app/current/tmp/pids/worker_01.pid
start program = "/bin/bash -c 'cd /app/current; RAILS_ENV=production QUEUE=batch_queue nohup
rake environment resque:work & > log/worker_01.log && echo $! > tmp/pids/worker_01.pid'" as uid
deploy and gid deploy
stop program = "/bin/bash -c 'cd /app/current && kill -s QUIT `cat tmp/pids/worker_01.pid` && rm
-f tmp/pids/worker_01.pid; exit 0;'"
if totalmem is greater than 1000 MB for 10 cycles then restart # eating up memory?
group resque_workers
@lmea #rubyday
35. Resque-status
Simple trackable jobs for resque
Job instances have a UUID
Jobs can report their status while running
@lmea #rubyday
36. Resque-status
# inheriting from JobWithStatus
class ExportJob < Resque::JobWithStatus
# perform is an instance method
def perform
limit = options['limit'].to_i || 1000
items = Item.limit(limit)
total = items.count
exported = []
items.each_with_index do |item, num|
at(num, total, "At #{num} of #{total}")
exported << item.to_csv
end
File.open(local_filename, 'w') { |f| f.write(exported.join("n")) }
complete(:filename=>local_filename)
end
end
@lmea #rubyday
37. Resque-status
job_id = SleepJob.create(:length => 100)
status = Resque::Status.get(job_id)
# the status object tell us:
status.pct_complete #=> 0
status.status #=> 'queued'
status.queued? #=> true
status.working? #=> false
status.time #=> Time object
status.message #=> "Created at ..."
Resque::Status.kill(job_id)
@lmea #rubyday
38. Resque-scheduler
Queueing for future execution
Scheduling jobs (like cron!)
@lmea #rubyday
39. Resque-scheduler
# run a job in 5 days
Resque.enqueue_in(5.days, SendFollowupEmail)
# run SomeJob at a specific time
Resque.enqueue_at(5.days.from_now, SomeJob)
@lmea #rubyday
40. Resque-scheduler
namespace :resque do
task :setup do
require 'resque'
require 'resque_scheduler'
require 'resque/scheduler'
Resque.redis = 'localhost:6379'
# The schedule doesn't need to be stored in a YAML, it just needs to
# be a hash. YAML is usually the easiest.
Resque::Scheduler.schedule = YAML.load_file('your_resque_schedule.yml')
# When dynamic is set to true, the scheduler process looks for
# schedule changes and applies them on the fly.
# Also if dynamic the Resque::Scheduler.set_schedule (and remove_schedule)
# methods can be used to alter the schedule
#Resque::Scheduler.dynamic = true
end
end
$ rake resque:scheduler
@lmea #rubyday
41. Resque-scheduler: the yaml configuration
queue_documents_for_indexing:
cron: "0 0 * * *"
class: QueueDocuments
queue: high
args:
description: "This job queues all content for indexing in solr"
export_items:
cron: "30 6 * * 1"
class: Export
queue: low
args: full
description: "This job does a weekly export"
@lmea #rubyday