I have developed Laravel application which allows dynamic subdomains. I mean single code for all tenants.each tenant will have separate database. But how can I setup crons for each subdomain?

Dani AI

Generated

As explained, a single codebase with dynamic subdomains and separate tenant databases makes creating an OS cron per subdomain both brittle and hard to maintain. A better pattern is one global system cron that runs Laravel's scheduler, and then let scheduled tasks iterate tenants and dispatch tenant-specific work (Artisan commands or queued jobs). That centralizes scheduling logic, avoids editing crontab for every tenant, and keeps environment bootstrapping consistent.

Use a single cron entry (absolute paths) and a scheduler closure that processes tenants in chunks:

* * * * * /usr/bin/php /path/to/artisan schedule:run >> /dev/null 2>&1

Example scheduling pattern in app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        \App\Models\Tenant::chunk(100, function($tenants) {
            foreach ($tenants as $tenant) {
                // switch DB for the tenant, then run a per-tenant Artisan command
                config(['database.connections.tenant.database' => $tenant->database]);
                \DB::purge('tenant');
                \DB::reconnect('tenant');

                \Artisan::call('tenant:task', ['tenant' => $tenant->id]);
            }
        });
    })->everyFiveMinutes();
}

Operational notes and cautions: avoid long, blocking loops inside schedule closures for large tenant counts — instead enqueue per-tenant jobs and run workers under Supervisor. Use chunking to limit memory, call DB::purge()/reconnect() after switching connections, and reset any cached state between tenants. Log failures per-tenant and add retry/timeout policies. For unique tenant schedules, store schedule metadata in the DB and have the global scheduler read it.

To answer : dynamically altering the system crontab is unnecessary and error-prone. A single schedule:run plus per-tenant commands or queued jobs is the robust, scalable approach; tenancy frameworks can add helpers for context switching if stronger isolation is required.

Recommended Answers

All 2 Replies

can anyone sugguest?

Hi,

in practice, your goal is to dynamically alter the crontab file? Or you're talking about something else?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.