GitHub

Queue Jobs

TinyMVC provides a simple yet powerful queue system for processing background jobs. Jobs can be scheduled for immediate or future execution with various priority levels.

Creating Jobs

Create jobs using the job() helper or by implementing JobContract:

// Simple job
job(function() {
    // Process data
    mailer(
        to: 'example@gmail.com', 
        subject: 'Data processed',
        body: 'Data processed successfully.'
    )->send();
})->dispatch();

Job Configuration

// Scheduled job
job(function() {
    // Send weekly report
})->schedule('next monday 8:00')->dispatch();

// Recurring job
job(function() {
    // Cleanup temporary files
})->repeat('daily')->dispatch();

// Priority job
job(function() {
    // Process critical payment
})->priority(100)->dispatch();

Job Lifecycle

job(function() {
    // Main job logic
})
->before(function() {
    // Prepare resources
})
->after(function() {
    // Cleanup resources
})
->catch(function($exception) {
    // Handle failures
})
->dispatch();

Dispatching Jobs

Use either the job helper or dispatch helper:

// Using job() helper
job(fn() => processData())->dispatch();

// Using dispatch() helper
dispatch(fn() => sendEmails());

Running Queue Workers

Local Development

# Process all queued jobs
php spark queue:run

# Clear all queued jobs
php spark queue:clear

Production Deployment

For production servers, set up a cron job to run the queue worker periodically:

cPanel Setup
  1. Go to cPanel → Cron Jobs
  2. Add a new cron job with timing (e.g. every 5 minutes): */5 * * * *
  3. Set the command to: cd /home/yourusername/public_html && php spark queue:run
Linux Server Setup
# Edit crontab
crontab -e

# Add this line to run every 5 minutes
*/5 * * * * cd /var/www/your-project && php spark queue:run >> /var/log/your-project-queue.log 2>&1
Windows Server Setup

Create a scheduled task that runs every 5 minutes with this command:

cd C:\path\to\your\project & php spark queue:run

Best Practices

Production Recommendations:
  • Run the queue worker every 5-10 minutes in production
  • Log job output for debugging
  • Use catch() to handle job failures gracefully
  • Monitor queue length and processing time

Advanced Examples

// Complex job with all options
job(function() use ($orderId) {
    $order = Order::find($orderId);
    $order->processPayment();
    $order->sendConfirmation();
})
->priority(200)
->schedule('+30 minutes')
->before(function() {
    db()->beginTransaction();
})
->after(function() {
    db()->commit();
})
->catch(function($e) {
    db()->rollback();
    notifyAdmins("Order processing failed: " . $e->getMessage());
})
->dispatch();

Troubleshooting

# Check if jobs are being queued
# (Verify your storage/queue.json file has job records)

# Test job execution manually
php spark queue:run

# Clear stuck jobs (if needed)
php spark queue:clear

# Verify cron is running
tail -f /var/log/cron.log