laravel-multitenancy icon indicating copy to clipboard operation
laravel-multitenancy copied to clipboard

Cannot schedule jobs in Laravel 11

Open dwrzos opened this issue 1 year ago • 3 comments

bootstrap.app file:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php')
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->group('auth-routes-tenant', [
            NeedsTenantForAuthRoutes::class,
            EnsureValidTenantSession::class,
        ]);

        $middleware->group('other-routes-tenant', [
            NeedsTenantForOtherRoutes::class,
            EnsureValidTenantSession::class,
        ]);

        $middleware->alias(['admin' => \App\Http\Middleware\AdminMiddleware::class]);
    })
    ->withSchedule(function (Schedule $schedule) {
        Tenant::all()->eachCurrent(function (Tenant $tenant) use ($schedule) {
            $schedule->job(new SaveFeedsJob())->everyFourHours();
            $schedule->job(new SaveSalesJob())->dailyAt('01:00');
        });
    })
    ->withExceptions()
    ->create();

SaveFeedsJob and SaveSalesJob are not dispatched, although scheduler is running.

Output of php artisan schedule:list when there are 2 tenants:

  0 */4 * * *  App\Jobs\SaveFeedsJob ...................................................... Next Due: in 3 hours
  0 1   * * *  App\Jobs\SaveSalesJob ...................................................... Next Due: in 16 hours
  0 */4 * * *  App\Jobs\SaveFeedsJob ...................................................... Next Due: in 3 hours
  0 1   * * *  App\Jobs\SaveSalesJob ...................................................... Next Due: in 16 hours

So looks like it should be dispatched for each tenant.

Queue connection is set to database. Jobs and failed jobs table are in landlord database.

What am I doing wrong?

dwrzos avatar May 10 '24 06:05 dwrzos

Please post a demo repo to test the issue.

masterix21 avatar May 12 '24 21:05 masterix21

Please post a demo repo to test the issue.

Repo

dwrzos avatar May 13 '24 06:05 dwrzos

Bit less elegant but I managed to make it work:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php')
    ->withSchedule(function (Schedule $schedule) {
        $schedule->call(function () {
            foreach (Tenant::all() as $tenant) {
                $tenant->makeCurrent();

                SaveFeedsJob::dispatch();
            }
        })->everyFourHours();

        $schedule->call(function () {
            foreach (Tenant::all() as $tenant) {
                $tenant->makeCurrent();

                SaveSalesJob::dispatch();
            }
        })->dailyAt('01:00');
    })
    ->withExceptions()
    ->create();

dwrzos avatar May 14 '24 18:05 dwrzos