# Recurring Background Jobs - Quick Start

## Overview

The ngauge-queues module now supports **auto-bootstrapping recurring jobs** that continuously run in the background. Jobs can be configured in two ways:

1. **Auto-Discovery** (Recommended): Add `public $recurringJob` property to job classes
2. **Explicit Config**: Define in `params-local.php`

Jobs automatically re-queue themselves at specified intervals, eliminating the need for external cron jobs.

## Quick Start - Auto-Discovery

Add a `recurringJob` property to your job class:

```php
namespace frontend\jobs;

class CartReminders extends BaseObject implements JobInterface
{
    // Every 4 hours (14400 seconds)
    public $recurringJob = 14400;
    
    public function execute($queue)
    {
        // Send cart reminders...
    }
}
```

That's it! The module will automatically discover and register this job on console app bootstrap.

## Or Use Explicit Config

Configure in `params-local.php` instead:

```php
return [
    'settings' => [
        'queues' => [
            'recurring' => [
                [
                    'class' => 'frontend\jobs\CartReminders',
                    'name' => 'Cart Reminders - Every 4 Hours',
                    'interval' => 14400,  // 4 hours in seconds
                    'enabled' => true,
                ],
            ],
        ],
    ],
];
```

See `AUTO_DISCOVERY.md` for detailed examples of auto-discovered jobs.

### 2. Your Job Class

Your existing job classes work as-is. No changes needed except adding the `$recurringJob` property for auto-discovery.

### 3. Start Supervisor

When you restart your supervisor workers, the module bootstrap will:
- Check for configured recurring jobs
- Start any enabled jobs that aren't already queued
- Jobs will run continuously at their configured intervals

## Advanced: Dynamic Control

Implement `RecurringJobInterface` for runtime control:

```php
namespace console\jobs;

use PortalPeople\queues\RecurringJobInterface;

class SmartJob extends BaseObject implements RecurringJobInterface
{
    public function execute($queue)
    {
        $count = $this->processItems();
        // Store for next run decision
        Yii::$app->cache->set('last_count', $count);
    }
    
    public function getRecurringInterval()
    {
        $count = Yii::$app->cache->get('last_count') ?? 0;
        // Adjust interval based on workload
        return $count > 100 ? 300 : 3600; // 5 min vs 1 hour
    }
    
    public function shouldContinue()
    {
        // Stop during maintenance mode
        return !Yii::$app->params['maintenanceMode'];
    }
}
```

## Configuration Options

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `class` | `string` | *required* | Job class name |
| `name` | `string` | auto | Human-readable name |
| `queue` | `string` | `'queue'` | Queue component |
| `interval` | `int` | `3600` | Seconds between runs |
| `ttr` | `int` | `300` | Max execution time |
| `enabled` | `bool` | `true` | Enable/disable |
| `checkDuplicates` | `bool` | `true` | Prevent duplicates |
| `maxRetries` | `int` | `3` | Retry attempts |
| `params` | `array` | `[]` | Job constructor params |

## Common Use Cases

### Cart Abandonment Emails (Every 4 Hours)
```php
[
    'class' => 'frontend\jobs\CartReminders',
    'interval' => 14400,
]
```

### NetSuite Order Sync (Every 15 Minutes)
```php
[
    'class' => 'console\jobs\UpdateOrders',
    'queue' => 'netsuitequeue',
    'interval' => 900,
    'ttr' => 600,
]
```

### Daily Cleanup (Once per Day)
```php
[
    'class' => 'frontend\jobs\Cleanup',
    'interval' => 86400,  // 24 hours
]
```

### Email Queue Processor (Every Minute)
```php
[
    'class' => 'common\jobs\ProcessEmails',
    'queue' => 'mailqueue',
    'interval' => 60,
]
```

## Monitoring

Recurring jobs appear in the queue dashboard at `/ngauge-queues` with their configured job names. You can monitor:

- Current pending count
- Running status
- Last execution time
- Stale job detection

## Stopping Recurring Jobs

To stop a recurring job:

1. **Disable in config**: Set `'enabled' => false`
2. **Restart supervisor**: Workers will pick up new config
3. **Manual removal**: Delete from `queue` table if needed

## Troubleshooting

### Job Not Starting
- Check `enabled => true` in config
- Verify supervisor is running
- Check console application logs for bootstrap errors

### Duplicate Jobs
- Keep `checkDuplicates => true` (default)
- Clear queue table before restarting if duplicates exist

### Job Not Re-queuing
- Check job execution doesn't throw exceptions
- Verify `shouldContinue()` returns `true` (if using interface)
- Check queue component exists

## See Also

- `AUTO_DISCOVERY.md` - How to use auto-discovery with `$recurringJob`
- `examples/auto_discovered_recurring_job.php` - Simple auto-discovery example
- `examples/auto_discovered_full_config.php` - Full config example
- `examples/recurring_jobs_example.php` - Explicit config examples
- `examples/custom_recurring_job_example.php` - Dynamic job example
- `README.md` - Module installation and usage
