Define scheduling tasks on modules (nwidart/laravel-modules:7.3) in Laravel 6

执行 schedule:run 命令 ,执行成功,且成功生成对应的日志文件
1. Generate a new module: blog.


PS E:wwwrootlaravel6-modules-demo> php artisan module:make Blog
Created : E:wwwrootlaravel6-modules-demoModules/Blog/module.json
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Routes/web.php
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Routes/api.php
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Resources/views/index.blade.php
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Resources/views/layouts/master.blade.php
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Config/config.php
Created : E:wwwrootlaravel6-modules-demoModules/Blog/composer.json
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Resources/assets/js/app.js
Created : E:wwwrootlaravel6-modules-demoModules/Blog/Resources/assets/sass/app.scss
Created : E:wwwrootlaravel6-modules-demoModules/Blog/webpack.mix.js
Created : E:wwwrootlaravel6-modules-demoModules/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, the module class will not load automatically. You can load your modules automatically using PSR-4. Edit composer.json. as shown in Figure 1
默认情况下,模块类不会自动加载。 你可以使用 psr-4 自动加载你的模块。编辑 composer.json
Figure 1


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


3. Tip: Don’t forget to run composer dump-autoload. as shown in Figure 2
提示:不要忘记之后运行 composer dump-autoload
Figure 2


PS E:wwwrootlaravel6-modules-demo> composer dump-autoload
Generating optimized autoload files
> IlluminateFoundationComposerScripts::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 a given console command for the specified module.


PS E:wwwrootlaravel6-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 modify the $name attribute and the handle method


<?php

namespace ModulesBlogConsole;

use IlluminateConsoleCommand;
use SymfonyComponentConsoleInputInputOption;
use SymfonyComponentConsoleInputInputArgument;

class CreatePostCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'blog:create-post';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        file_put_contents(storage_path() . '/logs/Modules-Blog-Console-CreatePostCommand-handle-' . microtime(true) . '-' . mt_rand()  . '.txt', print_r([], true), FILE_APPEND | LOCK_EX);
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['example', InputArgument::REQUIRED, 'An example argument.'],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null],
        ];
    }
}



6. Register the command to register the command using the Laravel method called Commands available in the service provider class.


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


7. To view the list of all available Artisan commands, you can use the list command: confirm that blog:create-post exists. as shown in Figure 3
要查看所有可用的 Artisan 命令的列表,可以使用 list 命令:确认 blog:create-post 已存在
Figure 3
8. Execute: php artisan blog:create-post When an error is reported: not enough arguments (missing: “example”).


PS E:wwwrootlaravel6-modules-demo&gt; php artisan blog:create-post


  Not enough arguments (missing: &quot;example&quot;).




9. Edit CreatePostCommand.php and delete the method getArguments 10. Execute again: php artisan blog:create-post, no more errors. To view the execution result, there is an output log file: modules-blog-console-createpostcommand-handle-1672371310.181-805184791.txt . as shown in Figure 4
再次执行:php artisan blog:create-post,不再报错。查看执行结果,有输出日志文件:Modules-Blog-Console-CreatePostCommand-handle-1672371310.181-805184791.txt
Figure 4
11. Execution: php artisan schedule:run, response: no scheduled command is ready to run.


PS E:wwwrootlaravel6-modules-demo&gt; php artisan schedule:run
No scheduled commands are ready to run.


12. Refer to task scheduling – ARTISAN command scheduling, define new scheduling tasks in the Schedule method of the AppConsoleKernel class


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


13. Execute the schedule:run command, the execution is successful, and the corresponding log file is successfully generated. as shown in Figure 5
执行 schedule:run 命令 ,执行成功,且成功生成对应的日志文件
Figure 5


PS E:wwwrootlaravel6-modules-demo&gt; php artisan schedule:run
Running scheduled command: &quot;C:php-7.4.27php.exe&quot; &quot;artisan&quot; blog:create-post &gt; &quot;NUL&quot; 2&gt;&amp;1


14. However, since command blog:create-post is written in the module, the schedule for scheduling this command should also be written in the corresponding module to be a more suitable implementation. 15. Reference: https://stackoverflow.com/questions/30456737/how-to-schedule-artisan-commands-in-a-package , both options are feasible. Restore the implementation of step 12.


    /**
     * 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();
        });
    }




PS E:wwwrootlaravel6-modules-demo&gt; php artisan schedule:run
Running scheduled command: &quot;C:php-7.4.27php.exe&quot; &quot;artisan&quot; blog:create-post &gt; &quot;NUL&quot; 2&gt;&amp;1
PS E:wwwrootlaravel6-modules-demo&gt; php artisan schedule:run
Running scheduled command: &quot;C:php-7.4.27php.exe&quot; &quot;artisan&quot; blog:create-post &gt; &quot;NUL&quot; 2&gt;&amp;1


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.