Background work for PHP applications:
- a job queue whose storage is a contract, with four adapters included: database (MySQL, MariaDB, PostgreSQL, SQLite), Redis, a file and in-memory;
- a task scheduler for interval and calendar schedules ("every 15 minutes", "weekdays at 08:00 Africa/Lagos", "monthly on the 1st");
- a queue worker that runs as a daemon, from cron, or inside a web request for a time budget;
- a runner that every trigger (crontab, a cron URL, a button) can share, with a lock, a throttle, a pause switch and heartbeats.
composer require callismart/backgroundIt requires PHP 8.1+, callismart/dto
and psr/container. The database adapter needs
callismart/dbprism; the Redis
adapter needs ext-redis (phpredis). The file and in-memory adapters need
nothing more.
A job is a class that implements JobHandlerInterface. The queue stores its
class name and a JSON payload; a worker builds the class and calls handle().
use Callismart\Background\Jobs\JobHandlerInterface;
final class SendWelcomeEmailJob implements JobHandlerInterface {
public function __construct( private Mailer $mailer ) {}
public function handle( array $payload = [] ) : mixed {
$this->mailer->send_welcome( (int) $payload['user_id'] );
return [ 'sent' => true ]; // Stored with the job; anything JSON can hold.
}
public static function get_job_name() : string {
return 'Send welcome email';
}
public static function get_job_description() : string {
return 'Sends the welcome email to a new user.';
}
}A job can run more than once (a retry, a worker killed mid-job), so make
handle() safe to repeat.
use Callismart\Background\Queue\JobDTO;
use Callismart\Background\Queue\JobQueue;
$queue = new JobQueue( $adapter );
$queue->push( SendWelcomeEmailJob::class, [ 'user_id' => 42 ] );
$queue->push( ResizeImageJob::class, [ 'id' => 7 ], JobDTO::QUEUE_LOW, priority: 8, delay: 60 );- Queues:
critical,defaultandlow. Workers take critical jobs first, then default, then low; within a queue, priority 1 (highest) to 10, then the oldest. - Retries: a failing job is retried until it has run
max_attemptstimes (3 by default), then moved to the failed jobs archive. By default a retry runs at once; pass a delay in seconds, or a callback for backoff:new JobQueue( $adapter, fn ( JobDTO $job ) : int => 30 * 2 ** $job->get( JobDTO::KEY_ATTEMPTS ) ). - Inspection and upkeep:
find_job(),get_jobs(),get_failed_jobs(),get_status_counts(),release_stale_running_jobs()(jobs whose worker died),purge_completed_jobs()andpurge_failed_jobs().
QueueAwareTrait adds dispatch_job(), dispatch_job_on_queue() and
dispatch_job_delayed() to a class that sets $this->job_queue.
Every adapter implements JobStorageAdapterInterface and passes the same
contract tests, including several processes claiming from one queue without
ever getting the same job.
| Adapter | ID | Use it for |
|---|---|---|
DatabaseJobStorageAdapter |
database |
Most applications: MySQL, MariaDB, PostgreSQL or SQLite through DBPrism. |
RedisJobStorageAdapter |
redis |
High job volumes; atomic Lua scripts. |
FileJobStorageAdapter |
file |
Small sites with no database or Redis: one JSON file, locked. |
InMemoryJobStorageAdapter |
memory |
Tests, and work that must not outlive the request. |
use Callismart\Background\Queue\Storage\DatabaseJobStorageAdapter;
use Callismart\Background\Queue\Storage\FileJobStorageAdapter;
use Callismart\Background\Queue\Storage\RedisJobStorageAdapter;
// Database: pass a connected Callismart\DBPrism\Database.
$adapter = new DatabaseJobStorageAdapter( $db, 'myapp_jobs', 'myapp_failed_jobs' );
$adapter->create_tables(); // Or build them in your migrations from DatabaseJobTables.
// Redis: a connected phpredis client, without a serializer or compression.
$redis = new Redis();
$redis->connect( '127.0.0.1', 6379 );
$adapter = new RedisJobStorageAdapter( $redis, 'myapp:jobs:' );
// File: on a local disk (flock() is unreliable on network file systems).
$adapter = new FileJobStorageAdapter( '/var/lib/myapp/queue.json' );Notes:
- Database: a claim locks the row (
SELECT … FOR UPDATE) and then updates it only if it is still waiting, so two workers can't take the same job, on SQLite too. PostgreSQL stores payloads asjsonb, which reorders object keys. - Redis: one hash per job and sorted sets for the indexes, changed only
by Lua scripts. The key prefix is added to the client's own
OPT_PREFIX. - File: reads and writes hold a lock file next to the queue file. Writes go to a temporary file renamed into place, so a crash never leaves half a file. A damaged file stops the queue with an error instead of being overwritten. Suits up to a few thousand jobs.
To store jobs anywhere else, implement JobStorageAdapterInterface; its
docblocks spell out the contract. The contract tests live in this repository
(tests/Support/StorageAdapterContractTestCase.php, not in the Composer
package): extend them to check your adapter.
use Callismart\Background\Workers\QueueWorker;
$worker = new QueueWorker( $queue, $container ); // A PSR-11 container builds handlers.
$worker = new QueueWorker( $queue, fn ( string $class ) => $factory->make( $class ) );
$worker = new QueueWorker( $queue ); // new $class() for handlers without arguments.
// A daemon kept alive by systemd or supervisord:
$worker->handle_signals(); // Finish the current job on SIGTERM/SIGINT (pcntl).
$worker->start_processing(); // Runs until stopped or the memory ceiling (128 MB).
// Inside cron or a web request:
$worker->process_within_time_budget( 25 );A job whose class is missing or is not a JobHandlerInterface fails like a
job that throws; it never stops the worker. set_logger() receives progress
lines; set_stop_checker() asks before each job whether to stop.
use Callismart\Background\Schedule\Scheduler;
use Callismart\Background\Schedule\State\FileScheduleStateStore;
$scheduler = new Scheduler(
new FileScheduleStateStore( '/var/lib/myapp/schedule.json' ),
$queue, // Optional: lets tasks dispatch jobs.
'Africa/Lagos' // Optional: time zone of calendar schedules. Default UTC.
);
$scheduler->call( 'prune-sessions', fn () => $sessions->prune() )->every_minutes( 15 );
$scheduler->call( 'report', [ $reports, 'send_daily' ] )->weekly_on( [ 1, 2, 3, 4, 5 ], '08:00' );
$scheduler->dispatch( BackupJob::class, [ 'full' => true ] )->daily_at( '02:30' )->timezone( 'UTC' );
$scheduler->synchronize_state(); // Optional: forget tasks you no longer register.
$scheduler->run_due_tasks();Schedules: minutely(), every_minutes( n ), hourly(), every_hours( n ),
daily(), daily_at( ...times ), every_days( n, ...times ), weekly(),
weekly_on( days, ...times ), monthly(), monthly_on( days, ...times )
(days 1–28), every_months( n, day, ...times ).
- An interval task runs on its first check, then every interval.
- A calendar task runs at its next slot. A late run never shifts later slots.
get_schedule_description()reads "Every 15 minutes" or "Daily at 08:00 (Africa/Lagos)".
The scheduler remembers when each task last ran through a state store:
FileScheduleStateStore, InMemoryScheduleStateStore, or
CallbackScheduleStateStore to keep it in your own settings or database:
new CallbackScheduleStateStore(
fn () : array => $settings->get( 'scheduler_state', [] ),
fn ( array $state ) => $settings->set( 'scheduler_state', $state )
);Call one runner from every trigger. It runs the due tasks, then the queue for a time budget (45 s on the command line, 25 s on the web), and returns what it did.
use Callismart\Background\BackgroundRunner;
use Callismart\Background\BackgroundStatus;
$status = new BackgroundStatus( '/var/lib/myapp/background.json' );
$runner = new BackgroundRunner( $scheduler, $worker, $status, '/var/lib/myapp/background.lock', $pause );
// From crontab, every minute: * * * * * php /path/to/app cron
$runner->run( BackgroundStatus::SOURCE_CRON );
// From a public cron URL: at most one run every 55 seconds.
$runner->run( BackgroundStatus::SOURCE_URL, min_interval: 55 );The result is ran (with tasks, failed, jobs and seconds), busy
(another run holds the lock), throttled, paused or updating.
- Pause: pass a
PauseSignalInterfacewhosereason()returns a reason while background work must hold, for example during an update or maintenance. The runner checks it before the run and between tasks and jobs.NeverPauseis the default. - Heartbeats:
BackgroundStatusrecords when each trigger last ran, so you can show "the scheduler last ran 40 seconds ago from cron (PHP 8.4)":$status->latest(),$status->age( 'cron' ). A long-running worker can record its own heartbeat with$status->record( BackgroundStatus::SOURCE_WORKER, [ 'pid' => getmypid() ] ).
Schedule descriptions, day names and the worker's error format are English by default. To translate them, hand the package your translator:
Callismart\Background\Translation::set_translator( fn ( string $text ) : string => my_translate( $text ) );composer install
vendor/bin/phpunit
composer cs:checkThe SQLite, file and in-memory adapters always run. The others run when their server is reachable:
| Variables | Default |
|---|---|
BACKGROUND_REDIS_HOST, BACKGROUND_REDIS_PORT |
127.0.0.1:6379 (skipped when unreachable) |
BACKGROUND_MYSQL_HOST, _PORT, _USER, _PASSWORD, _DB |
skipped without a host |
BACKGROUND_PGSQL_HOST, _PORT, _USER, _PASSWORD, _DB |
skipped without a host |
The database tests use the background_test database.
MIT