I have a project that needs to send notifications via WebSockets continuously. It should connect to a device that returns the overall status in string format. The system processes it and then sends notifications based on various conditions.
Since the scheduler can repeat a task as early as a minute, I need to find a way to execute the function every second.
Here is my app/Console/Kernel.php
:
<?php ... class Kernel extends ConsoleKernel { ... protected function schedule(Schedule $schedule) { $schedule->call(function(){ // connect to the device and process its response })->everyMinute(); } }
PS: If you have a better idea to handle the situation, please share your thoughts.
Advertisement
Answer
Usually, when you want more granularity than 1 minute, you have to write a daemon.
I advise you to try, now it’s not so hard as it was some years ago. Just start with a simple loop inside a CLI command:
while (true) { doPeriodicStuff(); sleep(1); }
One important thing: run the daemon via supervisord. You can take a look at articles about Laravel’s queue listener setup, it uses the same approach (a daemon + supervisord). A config section can look like this:
[program:your_daemon] command=php artisan your:command --env=your_environment directory=/path/to/laravel stdout_logfile=/path/to/laravel/app/storage/logs/your_command.log redirect_stderr=true autostart=true autorestart=true