没有不值得去解决的问题,也没有不值得去学习的技术!

Define Scheduled Tasks on Modules in Laravel 6

Execute the schedule:run command. It executes successfully and generates the corresponding log file

1. Generate a new module: Blog.

Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan module:make Blog
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/module.json
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Routes/web.php
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Routes/api.php
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Resources/views/index.blade.php
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Resources/views/layouts/master.blade.php
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Config/config.php
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/composer.json
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Resources/assets/js/app.js
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/Resources/assets/sass/app.scss
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/webpack.mix.js
Created : E:\wwwroot\laravel6-modules-demo\Modules/Blog/package.json
Created : E:/wwwroot/laravel6-modules-demo/Modules/Blog/Database/Seeders/BlogDatabaseSeeder.php
Created : E:/wwwroot/laravel6-modules-demo/Modules/Blog/Providers/BlogServiceProvider.php
Created : E:/wwwroot/laravel6-modules-demo/Modules/Blog/Providers/RouteServiceProvider.php
Created : E:/wwwroot/laravel6-modules-demo/Modules/Blog/Http/Controllers/BlogController.php
Module [Blog] created successfully.

2. By default, module classes are not autoloaded. You can use psr-4 to autoload your modules. Edit composer.json. See Figure 1.

By default, module classes are not autoloaded. You can use psr-4 to autoload your modules. Edit composer.json
Figure 1
Plaintext

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Modules\\": "Modules/"
        }
    },

3. Tip: Do not forget to run composer dump-autoload afterwards. See Figure 2.

Tip: Do not forget to run composer dump-autoload afterwards
Figure 2
Plaintext

PS E:\wwwroot\laravel6-modules-demo> composer dump-autoload
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: nwidart/laravel-modules
Package manifest generated successfully.
Generated optimized autoload files containing 4360 classes

4. Generate the given console command for the specified module.

Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan module:make-command CreatePostCommand Blog
Created : E:/wwwroot/laravel6-modules-demo/Modules/Blog/Console/CreatePostCommand.php

5. Edit CreatePostCommand.php, mainly modifying the $name property and the handle method.

6. Register the command using the Laravel method named commands available in the service provider class.

PHP

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(RouteServiceProvider::class);
        $this->commands([
            \Modules\Blog\Console\CreatePostCommand::class,
        ]);
    }

7. To view a list of all available Artisan commands, you can use the list command: confirm that blog:create-post already exists. See Figure 3.

To view a list of all available Artisan commands, you can use the list command: confirm that blog:create-post already exists
Figure 3

8. When executing: php artisan blog:create-post, an error is reported: Not enough arguments (missing: “example”).

Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan blog:create-post


  Not enough arguments (missing: "example").



9. Edit CreatePostCommand.php and remove the getArguments method.

10. Execute again: php artisan blog:create-post, and the error no longer occurs. Checking the execution result, there is an output log file: Modules-Blog-Console-CreatePostCommand-handle-1672371310.181-805184791.txt. See Figure 4.

Execute again: php artisan blog:create-post, and the error no longer occurs. Checking the execution result, there is an output log file: Modules-Blog-Console-CreatePostCommand-handle-1672371310.181-805184791.txt
Figure 4

11. Execute: php artisan schedule:run, response: No scheduled commands are ready to run.

Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan schedule:run
No scheduled commands are ready to run.

12. Referring to Task Scheduling – Scheduling Artisan Commands, define a new scheduled task in the schedule method of the App\Console\Kernel class.

PHP

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')
        //          ->hourly();
        $schedule->command('blog:create-post')->everyMinute(); // 每分钟执行一次任务
    }

13. Execute the schedule:run command. It executes successfully and generates the corresponding log file. See Figure 5.

Execute the schedule:run command. It executes successfully and generates the corresponding log file
Figure 5
Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan schedule:run
Running scheduled command: "C:\php-7.4.27\php.exe" "artisan" blog:create-post > "NUL" 2>&1

14. However, since the command blog:create-post is written inside the module, the schedule that schedules this command should also be written inside the corresponding module for a more appropriate implementation.

15. Reference: https://stackoverflow.com/questions/30456737/how-to-schedule-artisan-commands-in-a-package . Both approaches are viable. Revert the implementation from step 12.

PHP

    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->loadMigrationsFrom(module_path($this->moduleName, 'Database/Migrations'));
        /*
        $this->app->booted(function () {
            $schedule = $this->app->make(Schedule::class);
            $schedule->command('blog:create-post')->everyMinute();
        });
        */
        // 在 Laravel 6.10 及以上版本中:
        $this->callAfterResolving(Schedule::class, function (Schedule $schedule) {
            $schedule->command('blog:create-post')->everyMinute();
        });
    }

Plaintext

PS E:\wwwroot\laravel6-modules-demo> php artisan schedule:run
Running scheduled command: "C:\php-7.4.27\php.exe" "artisan" blog:create-post > "NUL" 2>&1
PS E:\wwwroot\laravel6-modules-demo> php artisan schedule:run
Running scheduled command: "C:\php-7.4.27\php.exe" "artisan" blog:create-post > "NUL" 2>&1

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系