Search code examples
laravellaravel-5cronscheduled-tasks

How i can run command by run schedule and by button also?


I have created commands in kernel.php which is running twiceDaily(). I also want to attach it with button so I can run this command by clicking on that button. When I click on on button it should run at that moment.

Currently, I have just created twiceDaily command I need better way to implement button idea.

kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->job(new \App\Jobs\ResendAttachment)->twiceDaily(1, 13);
}

I want to run command by cron job on server and by button also.


Solution

  • What you are doing now is scheduling a job to run twice daily. However, you can also manually dispatch a job to run at that instance (or as soon as a runner is free to handle your job).

    You can create a controller action so that when the button is clicked, the controller dispatch the job. For example,

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Jobs\ResendAttachment;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    
    class ExampleController extends Controller
    {
        /**
         * Resend attachment.
         *
         * @param  Request  $request
         * @return Response
         */
        public function resendAttachment(Request $request)
        {
            ResendAttachment::dispatch();
        }
    }