Skip to content

Instantly share code, notes, and snippets.

@bert-w
Created May 30, 2023 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bert-w/89a1bd46787c2404764bfd56f8a23fd1 to your computer and use it in GitHub Desktop.
Save bert-w/89a1bd46787c2404764bfd56f8a23fd1 to your computer and use it in GitHub Desktop.
Repeat Laravel commands every (few) second(s)
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class RepeatCommand extends Command
{
protected $signature = 'repeat-command
{command-string : The name of the command; extra parameters can be passed by encasing the whole string in double quotes}
{--duration=60 : The duration in seconds which defines how long the loop will run}
{--every=10 : The interval of the command}';
protected $description = 'Run artisan commands more often than once a minute, by defining an interval in seconds and a duration.';
public function handle()
{
$every = $this->option('every');
$duration = $this->option('duration');
$command = $this->argument('command-string');
for ($i = 0; $i < ($duration / $every); $i++) {
$start = $this->microtime();
Artisan::call($command, [], $this->output);
// Sleep for the given number of microseconds, subtracting the execution time.
sleep_us(($every * 1e6) - ($this->microtime() - $start));
}
}
/**
* Get the Unix time in microseconds (millionths of a second).
*/
private function microtime(): int
{
return (int)(microtime(true) * 1e6);
}
}
<?php
// ...
protected function schedule(Schedule $schedule)
{
$schedule->command(RepeatCommand::class, [
'somefastcommand', '--every' => 3, '--duration' => 60,
])->everyMinute()->runInBackground();
// ...
}
<?php
if (!function_exists('sleep_us')) {
/**
* Sleep the script for a given number of microseconds.
*
* @param int $microseconds
* @return void
*/
function sleep_us($microseconds)
{
if ($microseconds < 0) {
return;
}
if ($usleep = $microseconds % 1000000) {
usleep($usleep);
}
if ($sleep = ($microseconds - $usleep) / 1000000) {
sleep($sleep);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment