Developer Snippet Diary

Task Scheduling in laravel 10, Make your own cronjob and run it

Why this is important:

  • schduled tasks
  • In your controll
  • view history, moniter etc

Laravel actually allows two different ways to define scheduled tasks. 

1.

Your task schedule is defined in the app/Console/Kernel.php file's schedule method

In Kernel.php add follwing code it will execute every minute , also run command to make it working

 protected function schedule(Schedule $schedule)
{
        $schedule->call(function () {
            file_put_contents('public/cron_sync_emails.log', file_get_contents("https://abc.site/sync_emails")); //or any logic here
        })->everyMinute();
}

Run the command 

php artisan schedule:work //on local

On server SET THE CRON EVERY MINUTE

cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
OR
cd /home/boosxdf/abc.site/ && /usr/local/bin/php artisan schedule:run >/dev/null 2>&1  (WORKING ON NAMECHEAP)
OR
cd /home/boosxdf/abc.site/ && /usr/bin/php artisan schedule:run >/dev/null 2>&1

cd /path-to-your-project: Project directory

&&: This is a command separator that allows us to chain commands together.

php artisan schedule:run: This command runs the Laravel scheduler, which executes any scheduled tasks that are due to run.

>> /dev/null: This redirects the output of the command to /dev/null, which discards it.

2>&1: This redirects the standard error output to the same place as the standard output.

 

OPEN URL IN Cron job

curl "https://abc.site/cron_test" //working

 

DETAILED:

Overview of your scheduled tasks

php artisan schedule:list
// Run once per week on Monday at 1 PM...
$schedule->call(function () {
    //
})->weekly()->mondays()->at('13:00');
 
// Run hourly from 8 AM to 5 PM on weekdays...
$schedule->command('foo')
          ->weekdays()
          ->hourly()
          ->timezone('America/Chicago')
          ->between('8:00', '17:00');

2. routes/console.php Laravel also allows scheduling inside this file.

use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')->daily();

=======================
How to check if commands works
=======================
1.First Confirm the Commands Exist

php artisan schedule:list

if output shows
Command    Schedule
charity:send-reminders    daily at 08:00

2. Test the Command Manually

php artisan charity:send-reminders

If the command works, it will: • execute normally • show output • or perform its task (email, sync etc)

3. Test the Scheduler Manually

php artisan schedule:run

If nothing is scheduled for the current minute you will see something like: No scheduled commands are ready to run.
4. Force a Task to Run for Testing

Change temporarily to: ->everyMinute();
and again test using php artisan schedule:run

5. Cron Setup With 5 Minute Limit because of namecheap limit

cd /home/boosxdf/abc.site/ && /usr/local/bin/php artisan schedule:run >/dev/null 2>&1

 

What If Cron Runs at 08:02?

If the cron was configured like this: */5 * *  every five minutes at namecheap

and started at 08:02, the execution times might be:

08:02
08:07
08:12

In that situation, Laravel would miss the exact 08:00 window, and the task would not run that day.

However, most cron systems start cleanly at: 00, 05, 10, 15, 20...

Example Timeline: $schedule->command('charity:send-reminders')->dailyAt('08:00'); WORKS
Example Timeline: $schedule->command('charity:send-reminders')->dailyAt('08:00'); NOT WORKS

Time    Cron Runs    Task Runs
07:55    yes    no
08:00    yes    YES
08:05    yes    no
08:10    yes    no

 

Scheduling Shell Commands

The exec method may be used to issue a command to the operating system:

use Illuminate\Support\Facades\Schedule;
Schedule::exec('node /home/forge/script.js')->daily();
Schedule::exec('mysqldump dbname > backup.sql')->daily();
Schedule::exec('python3 /scripts/analyze.py')->daily();

Preventing Task Overlaps
By default, scheduled tasks will be run even if the previous instance of the task is still running. To prevent this, you may use the withoutOverlapping method:

use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')->withoutOverlapping();

the emails:send Artisan command will be run every minute if it is not already running.  By default, the lock will expire after 24 hours:

Task Output: The Laravel scheduler provides several convenient methods for working with the output generated by scheduled tasks. First, using the sendOutputTo method, you may send the output to a file for later inspection:

use Illuminate\Support\Facades\Schedule;
Schedule::command('emails:send')
    ->daily()
    ->sendOutputTo($filePath); //or     ->appendOutputTo($filePath);
Schedule::command('report:generate')
    ->daily()
    ->sendOutputTo($filePath)
    ->emailOutputTo('taylor@example.com');

 

 URL CALL USING SCHDULER:

$schedule->call(function () {
     $url = config('app.url') . '/api/coin-prices/sync';
     \Illuminate\Support\Facades\Http::get($url);
})->everyFiveMinutes()->withoutOverlapping();

 

https://laravel.com/docs/8.x/scheduling


Posted by: R GONDAL
Email: rizikmw@gmail.com