• This repository has been archived on 12/Apr/2022
  • Stars
    star
    254
  • Rank 160,264 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 14 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP port of delayed_job, a database backed asynchronous priority queue

DJJob

DJJob allows PHP web applications to process long-running tasks asynchronously. It is a PHP port of delayed_job (developed at Shopify), which has been used in production at SeatGeek since April 2010.

Like delayed_job, DJJob uses a jobs table for persisting and tracking pending, in-progress, and failed jobs.

Requirements

  • PHP5
  • PDO (Ships with PHP >= 5.1)
  • (Optional) PCNTL library

Setup

Import the sql database table.

mysql db < jobs.sql

The jobs table structure looks like:

CREATE TABLE `jobs` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`handler` TEXT NOT NULL,
`queue` VARCHAR(255) NOT NULL DEFAULT 'default',
`attempts` INT UNSIGNED NOT NULL DEFAULT 0,
`run_at` DATETIME NULL,
`locked_at` DATETIME NULL,
`locked_by` VARCHAR(255) NULL,
`failed_at` DATETIME NULL,
`error` TEXT NULL,
`created_at` DATETIME NOT NULL
) ENGINE = INNODB;

You may need to use BLOB as the column type for handler if you are passing in serialized blobs of data instead of record ids. For more information, see this link This may be the case for errors such as the following: unserialize(): Error at offset 2010 of 2425 bytes

Tell DJJob how to connect to your database:

DJJob::configure([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'dbname' => 'djjob',
    'user' => 'root',
    'password' => 'topsecret',
]);

Usage

Jobs are PHP objects that respond to a method perform. Jobs are serialized and stored in the database.

<?php
// Job class
class HelloWorldJob {
    public function __construct($name) {
        $this->name = $name;
    }
    public function perform() {
        echo "Hello {$this->name}!\n";
    }
}

// enqueue a new job
DJJob::enqueue(new HelloWorldJob("delayed_job"));

Unlike delayed_job, DJJob does not have the concept of task priority (not yet at least). Instead, it supports multiple queues. By default, jobs are placed on the "default" queue. You can specifiy an alternative queue like:

DJJob::enqueue(new SignupEmailJob("[email protected]"), "email");

At SeatGeek, we run an email-specific queue. Emails have a sendLater method which places a job on the email queue. Here's a simplified version of our base Email class:

class Email {
    public function __construct($recipient) {
        $this->recipient = $recipient;
    }
    public function send() {
        // do some expensive work to build the email: geolocation, etc..
        // use mail api to send this email
    }
    public function perform() {
        $this->send();
    }
    public function sendLater() {
        DJJob::enqueue($this, "email");
    }
}

Because Email has a perform method, all instances of the email class are also jobs.

Running the jobs

Running a worker is as simple as:

$worker = new DJWorker($options);
$worker->start();

Initializing your environment, connecting to the database, etc. is up to you. We use symfony's task system to run workers, here's an example of our jobs:worker task:

<?php
class jobsWorkerTask extends sfPropelBaseTask {
  protected function configure() {
    $this->namespace        = 'jobs';
    $this->name             = 'worker';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [jobs:worker|INFO] task runs jobs created by the DJJob system.
Call it with:

  [php symfony jobs:worker|INFO]
EOF;
    $this->addArgument('application', sfCommandArgument::OPTIONAL, 'The application name', 'customer');
    $this->addOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev');
    $this->addOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel');
    $this->addOption('queue', null, sfCommandOption::PARAMETER_REQUIRED, 'The queue to pull jobs from', 'default');
    $this->addOption('count', null, sfCommandOption::PARAMETER_REQUIRED, 'The number of jobs to run before exiting (0 for unlimited)', 0);
    $this->addOption('sleep', null, sfCommandOption::PARAMETER_REQUIRED, 'Seconds to sleep after finding no new jobs', 5);
}

  protected function execute($arguments = array(), $options = array()) {
    // Database initialization
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = Propel::getConnection($options['connection'] ? $options['connection'] : '');

    $worker = new DJWorker($options);
    $worker->start();
  }
}

The worker will exit if the database has any connectivity problems. We use god to manage our workers, including restarting them when they exit for any reason.

Changes

  • Eliminated Propel dependency by switching to PDO

More Repositories

1

fuzzywuzzy

Fuzzy String Matching in Python
Python
9,191
star
2

thefuzz

Fuzzy String Matching in Python
Python
2,813
star
3

react-infinite

A browser-ready efficient scrolling container based on UITableView
JavaScript
2,708
star
4

soulmate

Unmaintained, use Soulheart!
Ruby
1,057
star
5

SGImageCache

A flexible image caching library for image rich iOS applications
Objective-C
401
star
6

android-PlacesAutocompleteTextView

An address-autocompleting text field for Android
Java
280
star
7

hashi-helper

Disaster Recovery and Configuration Management for Consul and Vault
Go
185
star
8

nomad-helper

Useful tools for working with @hashicorp Nomad at scale
Go
158
star
9

docker-mirror

Mirror docker images across image repositories
Go
144
star
10

nomad-firehose

Firehose all nomad job, allocation, nodes and evaluations changes to rabbitmq, kinesis or stdout
Go
115
star
11

bash-aptfile

A simple method of defining apt-get dependencies for an application
Shell
92
star
12

businesstime

A simple python utility for calculating business time aware timedeltas between two datetimes
Python
84
star
13

react-slider

DEPRECATED: A Slider in React
JavaScript
80
star
14

docker-build-cacher

Builds a service with docker and caches the intermediate stages
Haskell
53
star
15

druzhba

Python
36
star
16

backstage-plugins

SeatGeek Backstage Plugins Collection
TypeScript
33
star
17

dhall-nomad

Create maintainable nomad job files
Dhall
25
star
18

conductor

A data-backed adwords campaign bidder
Python
25
star
19

haldane

a friendly http interface to the aws api
Python
23
star
20

SGHTTPRequest

Objective-C
17
star
21

tornado-async-transformer

libcst transformer that replaces tornado's legacy @gen.coroutine syntax with python3.5+ native async/await
Python
17
star
22

aws-dynamic-consul-catalog

Keep your Consul service catalog in sync with your RDS instances
Go
16
star
23

amqp-dispatcher

A daemon to run AMQP consumers
Python
14
star
24

statsd_rb

DEPRECATED. Use https://github.com/etsy/statsd instead of this.
Ruby
13
star
25

hell

Deprecated: Hell is an open source web interface that exposes a set of capistrano recipes as a json api, for usage within large teams
JavaScript
12
star
26

redis-health

Can be used to check the health of your Redis instance.
Go
12
star
27

SGAPI

The SG Api SDK for iOS
Objective-C
11
star
28

SGListAnimator

Provides animated transitions for your table and collection views, so you don't have to resort to calling `reloadData`.
Objective-C
10
star
29

api-support

A support channel for the SeatGeek Platform
9
star
30

react-select-option

A plain <select> component that can be styled.
JavaScript
8
star
31

circus-logstash

A Circus logger for shipping logs to Logstash
Python
6
star
32

nomad-crashloop-detector

detect Nomad allocation crash-loops, by consuming the allocation stream from nomad-firehose
Go
5
star
33

gramo

Kotlin
5
star
34

datadog-service-helper

use consul catalog to manage datadog service checks
Go
4
star
35

logrus-gelf-formatter

Formats logrus messages in the GELF JSON format
Go
4
star
36

wrecker-ui

An HTML interface for wrecker, the load testing tool
Elm
4
star
37

graceful_listener

net.Listener implementation for graceful shutdown
Go
4
star
38

sgcli

A command-line interface for SeatGeek
Python
4
star
39

geocoder-java

Fork of https://code.google.com/p/geocoder-java/
Java
3
star
40

homebrew-formulae

Custom SeatGeek Formula for Homebrew
Ruby
3
star
41

k8s-reconciler-generic

A generic Kubernetes reconciler abstraction based on kubebuilder
Go
3
star
42

sgmods-go

Codemods for golang from SeatGeek.
Go
1
star
43

api-intro-presentation

1
star
44

seatgeek-emea-ios-sdk

Swift
1
star
45

elastic-search-health

Go
1
star
46

greenhouse-api-client

Kotlin
1
star
47

vault-stress

Go
1
star
48

sfn-stack-profile

Ruby
1
star
49

eslint-config-seatgeek-react-standard

React rules specific to the SeatGeek repositories.
JavaScript
1
star