Skip to content
Mike Perham edited this page Jun 10, 2016 · 29 revisions

Want to run some background jobs in Sidekiq.cr? Let's get you started!

Create an App

Create a new Crystal application if necessary.

crystal init app sample

Integrate into your App

Pull in Sidekiq.cr as a dependency into your application in shards.yml:

dependencies:
  sidekiq:
    github: mperham/sidekiq.cr
    branch: master

Run shards update to download the Sidekiq source.

Create your First Worker

In src/sample/workers.cr:

require "sidekiq"

module Sample
  class MyWorker
    include Sidekiq::Worker

    def perform(x : Int64)
      logger.info "hello!"
    end
  end
end

Build the Sidekiq binary

With Crystal, you build and run a single binary with Sidekiq and all your worker code compiled into it. Put this in sidekiq.cr and then run it with crystal run sidekiq.cr:

require "sidekiq"
require "sidekiq/cli"
require "./src/sample"

cli = Sidekiq::CLI.new
server = cli.configure do |config|
  config.redis = ConnectionPool(Redis).new(capacity: 30, timeout: 5.0) do
    Redis.new(host: "localhost", port: 6379)
  end
end

cli.run(server)

You can build Sidekiq with crystal build sidekiq.cr and run ./sidekiq. It will print "hello!" up to 10x faster than Ruby, amazing!

Build the Web UI

Sidekiq also offers a Web UI to monitor the cluster of Sidekiq processes using Redis. Put this in web.cr, build with crystal build web.cr.

require "sidekiq/web"

Kemal.config do |config|
  # To enable SSL termination:
  # ./web --ssl --ssl-key-file your_key_file --ssl-cert-file your_cert_file
  #
  # For more options, including changing the listening port:
  # ./web --help
  #
  # Basic authentication:
  #
  # config.add_handler Kemal::Middleware::HTTPBasicAuth.new("username", "password")
end

pool = Sidekiq::Pool.new(
  ConnectionPool(Redis).new(capacity: 3, timeout: 5.0) do
    Redis.new(host: "localhost", port: 6379)
  end
)
Sidekiq::Client.default_context = Sidekiq::Client::Context.new(pool, Sidekiq::Logger.build)

Kemal.run

Run ./web and navigate to http://localhost:3000.

Clone this wiki locally