百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

cloudtasker

> 后端框架
开源

使用 Google Cloud 任务的 Ruby 后台作业

162 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

使用 Google Cloud 任务的 Ruby 后台作业

Cloudtasker

Background jobs for Ruby using Google Cloud Tasks.

Cloudtasker provides an easy to manage interface to Google Cloud Tasks for background job processing. Workers can be defined programmatically using the Cloudtasker DSL and enqueued for processing using a simple to use API.

Cloudtasker is particularly suited for serverless applications only responding to HTTP requests and where running a dedicated job processing server is not an option (e.g. deploy via Cloud Run). All jobs enqueued in Cloud Tasks via Cloudtasker eventually get processed by your application via HTTP requests.

Cloudtasker also provides optional modules for running cron jobs, batch jobs, unique jobs and storable jobs.

A local processing server is also available for development. This local server processes jobs in lieu of Cloud Tasks and allows you to work offline.

Summary

  1. Installation
  2. Get started with Rails
  3. Get started with Rails & ActiveJob
  4. Configuring Cloudtasker
    1. Cloud Tasks authentication & permissions
    2. Cloudtasker initializer
  5. Enqueuing jobs
  6. Managing worker queues
    1. Creating queues
    2. Assigning queues to workers
  7. Extensions
  8. Working locally
    1. Option 1: Cloudtasker local server
    2. Option 2: Using ngrok
  9. Logging
    1. Configuring a logger
    2. Logging context
    3. Truncating log arguments
    4. Searching logs: Job ID vs Task ID
  10. Error Handling
    1. HTTP Error codes
    2. Worker callbacks
    3. Global callbacks
    4. Max retries
    5. Conditional reenqueues using retry errors
    6. Dispatch deadline
  11. Testing
    1. Test helper setup
    2. In-memory queues
    3. Unit tests
  12. Best practices building workers

Installation

Add this line to your application's Gemfile:

ruby
gem 'cloudtasker'

And then execute:

$ bundle

Or install it yourself with:

$ gem install cloudtasker

Get started with Rails

Cloudtasker is pre-integrated with Rails. Follow the steps below to get started.

Install redis on your machine (this is required by the Cloudtasker local processing server)

bash
# E.g. using brew
brew install redis

Add the following initializer

ruby
# config/initializers/cloudtasker.rb

Cloudtasker.configure do |config|
  #
  # Adapt the server port to be the one used by your Rails web process
  #
  config.processor_host = 'http://localhost:3000'

  #
  # If you do not have any Rails secret_key_base defined, uncomment the following
  # This secret is used to authenticate jobs sent to the processing endpoint
  # of your application.
  #
  # config.secret = 'some-long-token'
end

Define your first worker:

ruby
# app/workers/dummy_worker.rb

class DummyWorker
  include Cloudtasker::Worker

  def perform(some_arg)
    logger.info("Job run with #{some_arg}. This is working!")
  end
end

Launch Rails and the local Cloudtasker processing server (or add cloudtasker to your foreman config as a worker process)

bash
# In one terminal
> rails s -p 3000

# In another terminal
> cloudtasker

Open a Rails console and enqueue some jobs

ruby
  # Process job as soon as possible
  DummyWorker.perform_async('foo')

  # Process job in 60 seconds
  DummyWorker.perform_in(60, 'foo')

  # Process job immediately, inline
  # Supported since: v0.15.0
  DummyWorker.perform_now('foo')

Your Rails logs should display the following:

…

That's it! Your job was picked up by the Cloudtasker local server and sent for processing to your Rails web process.

Now jump to the next section to configure your app to use Google Cloud Tasks as a backend.

Get started with Rails & ActiveJob

Note: ActiveJob is supported since 0.11.0
Note: Cloudtasker extensions (cron, batch, unique jobs and storable) are not available when using cloudtasker via ActiveJob.

Cloudtasker is pre-integrated with ActiveJob. Follow the steps below to get started.

Install redis on your machine (this is required by the Cloudtasker local processing server)

bash
# E.g. using brew
brew install redis

Add the following initializer

ruby
# config/initializers/cloudtasker.rb

Cloudtasker.configure do |config|
  #
  # Adapt the server port to be the one used by your Rails web process
  #
  config.processor_host = 'http://localhost:3000'

  #
  # If you do not have any Rails secret_key_base defined, uncomment the following
  # This secret is used to authenticate jobs sent to the processing endpoint
  # of your application.
  #
  # config.secret = 'some-long-token'
end

Configure ActiveJob to use Cloudtasker. You can also configure ActiveJob per environment via the config/environments/:env.rb files

ruby
# config/application.rb

require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module Dummy
  class Application  rails s -p 3000

# In another terminal
> cloudtasker

Open a Rails console and enqueue some jobs

ruby
  # Process job as soon as possible
  ExampleJob.perform_later('foo')

  # Process job in 60 seconds
  ExampleJob.set(wait: 60).perform_later('foo')

Configuring Cloudtasker

Cloud Tasks authentication & permissions

The Google Cloud library authenticates via the Google Cloud SDK by default. If you do not have it setup then we recommend you install it.

Other options are available such as using a service account. You can see all authentication options in the Google Cloud Authentication guide.

In order to function properly Cloudtasker requires the authenticated account to have the following IAM permissions:

  • cloudtasks.tasks.get
  • cloudtasks.tasks.create
  • cloudtasks.tasks.delete

To get started quickly you can add the roles/cloudtasks.admin role to your account via the IAM Console. This is not required if your account is a project admin account.

The GCP project ID and region values are not loaded automatically by the Google Cloud library, and must be explicitly defined in the initializer when using Google Cloud Tasks.

Cloudtasker initializer

The gem can be configured through an initializer. See below all the available configuration options.

…

If the default queue -default does not exist in Cloud Tasks you should create it using the gcloud sdk.

Alternatively with Rails you can simply run the following rake task if you have queue admin permissions (cloudtasks.queues.get and cloudtasks.queues.create).

bash
bundle exec rake cloudtasker:setup_queue

Enqueuing jobs

Cloudtasker provides multiple ways of enqueuing jobs.

…

Cloudtasker also provides a helper for re-enqueuing jobs. Re-enqueued jobs keep the same job id. Some middlewares may rely on this to track the fact that that a job didn't actually complete (e.g. Cloustasker batch). This is optional and you can always fallback to using exception management (raise an error) to retry/re-enqueue jobs.

E.g.

ruby
# app/workers/fetch_resource_worker.rb

class FetchResourceWorker
  include Cloudtasker::Worker

  def perform(id)
    # ...do some logic...
    if some_condition
      # Stop and re-enqueue the job to be run again in 10 seconds.
      # Also see the section on Cloudtasker::RetryWorkerError for a different
      # approach on reenqueuing.
      return reenqueue(10)
    else
      # ...keep going...
    end
  end
end

Managing worker queues

Cloudtasker allows you to manage several queues and distribute workers across them based on job priority. By default jobs are pushed to the default queue, which is -default in Cloud Tasks.

Creating queues

More queues can be created using the gcloud sdk or the cloudtasker:setup_queue rake task.

E.g. Create a critical queue with a concurrency of 5 via the gcloud SDK

bash
gcloud tasks queues create -critical --max-concurrent-dispatches=5

E.g. Create a real-time queue with a concurrency of 15 via the rake task (Rails only)

bash
rake cloudtasker:setup_queue name=real-time concurrency=15

When running the Cloudtasker local processing server, you can specify the concurrency for each queue using:

bash
cloudtasker -q critical,5 -q important,4 -q default,3

Assigning queues to workers

Queues can be assigned to workers via the cloudtasker_options directive on the worker class:

ruby
# app/workers/critical_worker.rb

class CriticalWorker
  include Cloudtasker::Worker

  cloudtasker_options queue: :critical

  def perform(some_arg)
    logger.info("This is a critical job run with arg=#{some_arg}.")
  end
end

Queues can also be assigned at runtime when scheduling a job:

ruby
CriticalWorker.schedule(args: [1], queue: :important)

Propagating the queue in child workers

Supported since: v0.15.0

You can specify propagate_queue: true via the cloudtasker_options to make workers enqueued inside a job use the runtime queue instead of the default (class-configured or default) queue:

ruby
# app/workers/child_worker.rb

class ChildWorker
  include Cloudtasker::Worker

  cloudtasker_options queue: :level2

  def perform(some_arg)
    logger.info("This is a child job, which is set to run on the level2 queue by default.")
  end
end
…

Extensions

Note: Extensions are not available when using cloudtasker via ActiveJob.

Cloudtasker comes with three optional features:

  • Cron Jobs [docs]: Run jobs at fixed intervals.
  • Batch Jobs [docs]: Run jobs in jobs and track completion of the overall batch.
  • Unique Jobs [docs]: Ensure uniqueness of jobs based on job arguments.
  • Storable Jobs [docs]: Park jobs until they are ready to be enqueued.

Working locally

Cloudtasker pushes jobs to Google Cloud Tasks, which in turn sends jobs for processing to your application via HTTP POST requests to the /cloudtasker/run endpoint of the publicly accessible domain of your application.

When working locally on your application it is usually not possible to have a public domain. So what are the options?

Option 1: Cloudtasker local server

The Cloudtasker local server is a ruby daemon that looks for jobs pushed to Redis and sends them to your application via HTTP POST requests. The server mimics the way Google Cloud Tasks works, but locally!

You can configure your application to use the Cloudtasker local server using the following initializer:

ruby
# config/initializers/cloudtasker.rb

Cloudtasker.configure do |config|
  # ... other options

  # Push jobs to redis and let the Cloudtasker local server collect them
  # This is the default mode unless CLOUDTASKER_ENV or RAILS_ENV or RACK_ENV is set
  # to a non-development environment
  config.mode = :development
end

The Cloudtasker server can then be started using:

bash
bundle exec cloudtasker

You can as well define a Procfile to manage the cloudtasker process via foreman. Then

Issues· 13 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubybackground-jobscloud-taskscloudtaskercron-jobs

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架