Logo

0x3d.Site

is designed for aggregating information.
Welcome
check repository here

Que

Build Status Coverage Status Version Downloads License

Simple Background Job Processing in Elixir :zap:

Que is a job processing library backed by Mnesia, a distributed real-time database that comes with Erlang / Elixir. That means it doesn't depend on any external services like Redis for persisting job state. This makes it really easy to use since you don't need to install anything other than Que itself.

See the Documentation.


Installation

Add que to your project dependencies in mix.exs:

def deps do
  [{:que, "~> 0.10.1"}]
end

and then add it to your list of applications:

def application do
  [applications: [:que]]
end

Mnesia Setup

Que runs out of the box, but by default all jobs are stored in-memory. To persist jobs across application restarts, specify the DB path in your config.exs:

config :mnesia, dir: 'mnesia/#{Mix.env}/#{node()}'        # Notice the single quotes

And run the following mix task:

$ mix que.setup

This will create the Mnesia schema and job database for you. For a detailed guide, see the Mix Task Documentation. For compiled releases where Mix is not available see this.


Usage

Que is very similar to other job processing libraries such as Ku and Toniq. Start by defining a Worker with a perform/1 callback to process your jobs:

defmodule App.Workers.ImageConverter do
  use Que.Worker

  def perform(image) do
    ImageTool.save_resized_copy!(image, :thumbnail)
    ImageTool.save_resized_copy!(image, :medium)
  end
end

You can now add jobs to be processed by the worker:

Que.add(App.Workers.ImageConverter, some_image)
#=> {:ok, %Que.Job{...}}

Pattern Matching

The argument here can be any term from a Tuple to a Keyword List or a Struct. You can also pattern match and use guard clauses like any other method:

defmodule App.Workers.NotificationSender do
  use Que.Worker

  def perform(type: :like, to: user, count: count) do
    User.notify(user, "You have #{count} new likes on your posts")
  end

  def perform(type: :message, to: user, from: sender) do
    User.notify(user, "You received a new message from #{sender.name}")
  end

  def perform(to: user) do
    User.notify(user, "New activity on your profile")
  end
end

Concurrency

By default, all workers process one Job at a time, but you can customize that by passing the concurrency option:

defmodule App.Workers.SignupMailer do
  use Que.Worker, concurrency: 4

  def perform(email) do
    Mailer.send_email(to: email, message: "Thank you for signing up!")
  end
end

Job Success / Failure Callbacks

The worker can also export optional on_success/1 and on_failure/2 callbacks that handle appropriate cases.

defmodule App.Workers.ReportBuilder do
  use Que.Worker

  def perform({user, report}) do
    report.data
    |> PDFGenerator.generate!
    |> File.write!("reports/#{user.id}/report-#{report.id}.pdf")
  end

  def on_success({user, _}) do
    Mailer.send_email(to: user.email, subject: "Your Report is ready!")
  end

  def on_failure({user, report}, error) do
    Mailer.send_email(to: user.email, subject: "There was a problem generating your report")
    Logger.error("Could not generate report #{report.id}. Reason: #{inspect(error)}")
  end
end

Setup and Teardown

You can similarly export optional on_setup/1 and on_teardown/1 callbacks that are respectively run before and after the job is performed (successfully or not). But instead of the job arguments, they pass the job struct as an argument which holds a lot more internal details that can be useful for custom features such as logging, metrics, requeuing and more.

defmodule MyApp.Workers.VideoProcessor do
  use Que.Worker

  def on_setup(%Que.Job{} = job) do
    VideoMetrics.record(job.id, :start, process: job.pid, status: :starting)
  end

  def perform({user, video, options}) do
    User.notify(user, "Your video is processing, check back later.")
    FFMPEG.process(video.path, options)
  end

  def on_teardown(%Que.Job{} = job) do
    {user, video, _options} = job.arguments
    link = MyApp.Router.video_path(user.id, video.id)

    VideoMetrics.record(job.id, :end, status: job.status)
    User.notify(user, "We've finished processing your video. See the results.", link)
  end
end

Head over to Hexdocs for detailed Worker documentation.


Roadmap

  • Write Documentation
  • Write Tests
  • Persist Job State to Disk
    • Provide an API to interact with Jobs
  • Add Concurrency Support
    • Make jobs work in Parallel
    • Allow customizing the number of concurrent jobs
  • Success/Failure Callbacks
  • Find a more reliable replacement for Amnesia
  • Delayed Jobs
  • Allow job cancellation
  • Job Priority
  • Support running in a multi-node enviroment
    • Recover from node failures
  • Support for more Persistence Adapters
    • Redis
    • Postgres
  • Mix Task for creating Mnesia Database
  • Better Job Failures
    • Option to set timeout on workers
    • Add strategies to automatically retry failed jobs
  • Web UI

Contributing

  • Fork, Enhance, Send PR
  • Lock issues with any bugs or feature requests
  • Implement something from Roadmap
  • Spread the word :heart:

License

This package is available as open source under the terms of the MIT License.


Elixir
Elixir
Elixir is a dynamic, functional programming language designed for building scalable and maintainable applications. Built on the Erlang VM, it's known for its high concurrency and fault tolerance, making it ideal for real-time systems and web services.
GitHub - chrismccord/atlas: Object Relational Mapper for Elixir
GitHub - chrismccord/atlas: Object Relational Mapper for Elixir
GitHub - mbuhot/ecto_job: Transactional job queue with Ecto, PostgreSQL and GenStage
GitHub - mbuhot/ecto_job: Transactional job queue with Ecto, PostgreSQL and GenStage
GitHub - zamith/tomlex: A TOML parser for elixir
GitHub - zamith/tomlex: A TOML parser for elixir
GitHub - pablomartinezalvarez/glayu: A static site generator for mid-sized sites.
GitHub - pablomartinezalvarez/glayu: A static site generator for mid-sized sites.
GitHub - jui/mustachex: Mustache for Elixir
GitHub - jui/mustachex: Mustache for Elixir
GitHub - joaothallis/elixir-auto-test: Run test when file is saved
GitHub - joaothallis/elixir-auto-test: Run test when file is saved
GitHub - campezzi/ignorant: Simplify comparison of Elixir data structures by ensuring fields are present but ignoring their values.
GitHub - campezzi/ignorant: Simplify comparison of Elixir data structures by ensuring fields are present but ignoring their values.
GitHub - Driftrock/mockingbird: A set of helpers to create http-aware modules that are easy to test.
GitHub - Driftrock/mockingbird: A set of helpers to create http-aware modules that are easy to test.
GitHub - gutschilla/elixir-pdf-generator: Create PDFs with wkhtmltopdf or puppeteer/chromium from Elixir.
GitHub - gutschilla/elixir-pdf-generator: Create PDFs with wkhtmltopdf or puppeteer/chromium from Elixir.
GitHub - antirez/disque: Disque is a distributed message broker
GitHub - antirez/disque: Disque is a distributed message broker
GitHub - jcomellas/ex_hl7: HL7 Parser for Elixir
GitHub - jcomellas/ex_hl7: HL7 Parser for Elixir
GitHub - Cirru/parser.ex: Cirru Parser in Elixir
GitHub - Cirru/parser.ex: Cirru Parser in Elixir
GitHub - thiamsantos/pwned: Check if your password has been pwned
GitHub - thiamsantos/pwned: Check if your password has been pwned
GitHub - suvash/hulaaki: DEPRECATED : An Elixir library (driver) for clients communicating with MQTT brokers(via the MQTT 3.1.1 protocol).
GitHub - suvash/hulaaki: DEPRECATED : An Elixir library (driver) for clients communicating with MQTT brokers(via the MQTT 3.1.1 protocol).
GitHub - sinetris/factory_girl_elixir: Minimal implementation of Ruby's factory_girl in Elixir.
GitHub - sinetris/factory_girl_elixir: Minimal implementation of Ruby's factory_girl in Elixir.
GitHub - navinpeiris/ex_unit_notifier: Desktop notifications for ExUnit
GitHub - navinpeiris/ex_unit_notifier: Desktop notifications for ExUnit
GitHub - DefactoSoftware/test_selector: Elixir library to help selecting the right elements in your tests.
GitHub - DefactoSoftware/test_selector: Elixir library to help selecting the right elements in your tests.
GitHub - xerions/ecto_migrate: Automatic migrations for ecto
GitHub - xerions/ecto_migrate: Automatic migrations for ecto
GitHub - meh/reagent: You need more reagents to conjure this server.
GitHub - meh/reagent: You need more reagents to conjure this server.
GitHub - stevegraham/hypermock: HTTP request stubbing and expectation Elixir library
GitHub - stevegraham/hypermock: HTTP request stubbing and expectation Elixir library
GitHub - msharp/elixir-statistics: Statistical functions and distributions for Elixir
GitHub - msharp/elixir-statistics: Statistical functions and distributions for Elixir
GitHub - Joe-noh/colorful: colorful is justice
GitHub - Joe-noh/colorful: colorful is justice
GitHub - ijcd/taggart: HTML as code in Elixir
GitHub - ijcd/taggart: HTML as code in Elixir
Build software better, together
Build software better, together
GitHub - yeshan333/ex_integration_coveralls: A library for run-time system code line-level coverage analysis.
GitHub - yeshan333/ex_integration_coveralls: A library for run-time system code line-level coverage analysis.
GitHub - PSPDFKit-labs/cobertura_cover: Output test coverage information in Cobertura-compatible format
GitHub - PSPDFKit-labs/cobertura_cover: Output test coverage information in Cobertura-compatible format
GitHub - basho/enm: Erlang driver for nanomsg
GitHub - basho/enm: Erlang driver for nanomsg
GitHub - pawurb/ecto_psql_extras: Ecto PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
GitHub - pawurb/ecto_psql_extras: Ecto PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
GitHub - crate/craterl: Client Libraries for Erlang
GitHub - crate/craterl: Client Libraries for Erlang
GitHub - sheharyarn/ecto_rut: Ecto Model shortcuts to make your life easier! :tada:
GitHub - sheharyarn/ecto_rut: Ecto Model shortcuts to make your life easier! :tada:
Elixir
More on Elixir

Programming Tips & Tricks

Code smarter, not harder—insider tips and tricks for developers.

Error Solutions

Turn frustration into progress—fix errors faster than ever.

Shortcuts

The art of speed—shortcuts to supercharge your workflow.
  1. Collections 😎
  2. Frequently Asked Question's 🤯

Tools

available to use.

Made with ❤️

to provide resources in various ares.