2

I have created a UniqueMessage class which I want to use in log statements inside /Console/Kernel::schedule() to suppress repeated log messages. I have tried to make an instance of my UniqueMessage class in the constructor for Kernel but it seems to me that the Kernel scheduler is run in a separate process for each run resulting in a new UniqueMessage instance for each run. So then the suppressing does not work. A workaround could be to instantiate my UniqueMessage outside of Kernel. But where should I do this?

Based on Best Ways To Define Global Variable In Laravel I assume I could create an instance in app/Providers/AppServiceProvider::boot(). The example here is using View Composers but I am not going to use the variables in views but in the Kernel class. So what is the best way to make an instance of my UniqueMessage available (globally) for the Kernal instance (process)?

Tried:

use App\Services\UniqueMessage;

class Kernel extends ConsoleKernel
{
    protected static $um;
    
    /**
     * Constructor
     */
    public function __construct(Application $app, Dispatcher $events)
    {
        parent::__construct($app, $events);
        $max=env('LOGACCS');
        if (!isset(self::$um)) { self::$um=new UniqueMessage($max, ['Illuminate\Support\Facades\Log', 'info']); }
    }
...

Expected:

Expected static $um to be truly static across each schedule run.

Arne
  • 31
  • 2
  • 1
    `schedule:run` is always run in a new process every minute (if you correctly configured the `cron`). First of all, do not use `env` outside a `config/***.php` file, because when you run `php artisan config:cache` in production, `env` will always return `null`, but not `config(...)`. Second, I would use Redis or something similar to store the "current" amount of logs or whatever number/value you want to store, so when the class is loaded, it read Redis and gets the current value, and when it is done, you store the latest value... but that could bring some concurrency issues... we need more info – matiaslauriti Mar 03 '23 at 18:49
  • Thank you for the advice on env vs config matiaslauriti I wasn’t aware of that. Since I currently only have 1 scheduled job concurrence should not be an issue now. Introducing Redis just for this seem to be overkill so for now I think I will simply reduce the frequency of scheduled task. – Arne Mar 04 '23 at 09:14
  • @Arne you can also just use a file cache to act in a similar way to redis or whatever cache you are using will do the same :) – mrhn Mar 06 '23 at 10:06

0 Answers0