Skip to content

Instantly share code, notes, and snippets.

@tobz-nz
Last active May 18, 2023 01:18
Show Gist options
  • Select an option

  • Save tobz-nz/78c43d61636f571239eaf8454237c726 to your computer and use it in GitHub Desktop.

Select an option

Save tobz-nz/78c43d61636f571239eaf8454237c726 to your computer and use it in GitHub Desktop.
An Artisan command to install/setup the Laravel Task Scheduler. It supports both Linux and Windows.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;
class InstallScheduler extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:install-scheduler';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Installs the artisan scheduler to Crontab/TaskScheduler.';
/**
* Execute the console command.
*/
public function handle()
{
$artisan = base_path('artisan');
$schedulerName = match (PHP_OS_FAMILY) {
'Windows' => 'TaskScheduler',
default => 'Crontab',
};
switch (PHP_OS_FAMILY) {
case 'Windows':
// need the full path to php.exe
$phpPath = Process::run('where php')->throw()->output();
// '/ru "SYSTEM"' means run in the background (don't open terminal window)
$command = sprintf(
'schtasks /create /tn "Laravel Scheduler" /tr "%s %s schedule:run" /sc minute /mo 1 /ru "SYSTEM"',
$phpPath,
$artisan
);
break;
default:
$command = '(crontab -l; echo "* * * * * php ' . $artisan . ' schedule:run >> /dev/null 2>&1") | crontab -';
}
if ($this->confirm("This will install the Artisan Scheduler to the $schedulerName. Continue?")) {
Process::run($command)->throw();
$this->info('Scheduler installed successfully.');
}
return Command::SUCCESS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment