spatie / laravel-multitenancy

Make your Laravel app usable by multiple tenants
https://spatie.be/docs/laravel-multitenancy
MIT License
1.11k stars 153 forks source link

Cannot schedule jobs in Laravel 11 #534

Closed dwrzos closed 3 months ago

dwrzos commented 6 months ago

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?

masterix21 commented 5 months ago

Please post a demo repo to test the issue.

dwrzos commented 5 months ago

Please post a demo repo to test the issue.

Repo

dwrzos commented 5 months ago

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();