Schedule Management

Tutorial 3 of 4

Laravel Task Scheduling Tutorial

1. Introduction

Goal: By the end of this tutorial, you will learn how to manage tasks scheduling in Laravel, which allows you to automate tasks that run at specific intervals.

Learning Outcomes:
- Understand task scheduling in Laravel.
- Create tasks that run at specified intervals.
- Manage scheduled tasks.

Prerequisites:
- Basic knowledge of PHP and Laravel.
- Laravel environment set up on your local machine.

2. Step-by-Step Guide

Laravel's task scheduling setup is done via the 'Console Kernel' class. This class has a method schedule that is used to define your task schedule.

Creating a Task

You can create a console command using the Artisan CLI tool by running the command php artisan make:command TestCommand. This will create a new command class in the app/Console/Commands directory.

Scheduling a Task

To schedule a task, you can add a new call to the command method within the schedule method of your app/Console/Kernel.php file.

3. Code Examples

Creating a Command

php artisan make:command TestCommand

This will generate:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestCommand extends Command
{
    protected $signature = 'command:name';

    protected $description = 'Command description';

    public function handle()
    {
        //
    }
}

$signature is where you define the command name, and $description is where you describe what the command does. The handle method is where the logic of the command is defined.

Scheduling a Command

Inside app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
   $schedule->command('command:name')->hourly();
}

This command will run every hour.

4. Summary

In this tutorial, we learned how to create and schedule tasks in Laravel. You should now be able to automate tasks that run at specific intervals.

Next Steps:
- Try to schedule different types of tasks (daily, weekly, etc.).
- Learn more about task output and how to send output to email.

Additional Resources:
- Laravel Official Documentation

5. Practice Exercises

Exercise 1: Create a task that runs every day at noon.

Solution:

protected function schedule(Schedule $schedule)
{
   $schedule->command('command:name')->dailyAt('12:00');
}

Exercise 2: Create a task that runs every Monday at 4:30 PM.

Solution:

protected function schedule(Schedule $schedule)
{
   $schedule->command('command:name')->weeklyOn(1, '16:30');
}

Tips for Further Practice: Try to schedule tasks that send email notifications, write to logs or clean up old data.