Schedule and unschedule eloquent models elegantly without cron jobs

Overview

Laravel Schedulable Logo

Laravel Schedulable Twitter

Schedule and Unschedule any eloquent model elegantly without cron job.

Salient Features:

  1. Turn any Eloquent Model into a schedulable one by using Schedulable trait in the model.

  2. Schedule Models to a time in future and they will be returned in query results at specified date and time.

  3. Reschedule and Unschedule at any time using simple methods.

  4. Hook into the model's life cycle via custom model events provided by the package.

  5. Override the default column name and use your own custom column name.

Some example use cases when this package can be useful:

  1. A Blog type application which allows bloggers to schedule their post to go public on a future date and time.

  2. An E-commerce website where the items in the inventory can be added at any time from the admin panel but they can be scheduled to be made available to the customers at a particular date and time.

Minimum Requirements

  1. Laravel 6.0
  2. PHP 7.2

Installation

composer require neelkanthk/laravel-schedulable

Usage

1. Create a migration to add schedule_at column in any table using package's scheduleAt(); method which creates a column with name schedule_at.

NOTE: If you want to use any other column name then simply use the $table->timestamp('column_name'); method as shown below in examples.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddScheduleAtColumnInPosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->scheduleAt(); //Using default schedule_at column
			//or
            $table->timestamp('publish_at', 0)->nullable(); //Using custom column name
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('schedule_at'); //Using default schedule_at column
            //or
            $table->dropColumn('publish_at'); //Using custom column name
        });
    }
}

2. Use the Neelkanth\Laravel\Schedulable\Traits\Schedulable trait in any Model.

NOTE: If you have used a custom column name in the migration then you have to specify that column in the Model as shown below.

use Illuminate\Database\Eloquent\Model;
use Neelkanth\Laravel\Schedulable\Traits\Schedulable;

class Post extends Model
{
    use Schedulable;
    
    const SCHEDULE_AT = "publish_at"; //Specify the custom column name
}

Usage

1. Scheduling a model

$scheduleAt = Carbon::now()->addDays(10); //Carbon is just an example. You can pass any object which is implementing DateTimeInterface.
$post = new App\Post();
//Add values to other attributes
$post->scheduleWithoutSaving($scheduleAt); // Modifies the schedule_at attribute and returns the current model object without saving it.
$post->schedule($scheduleAt); //Saves the model in the database and returns boolean true or false

2. Unscheduling a model

$post = App\Post::find(1);
$post->unscheduleWithoutSaving(); // Modifies the schedule_at attribute and returns the current model object without saving it.
$post->unschedule(); //Saves the model in the database and returns boolean true or false

3. Events and Observers

The package provides four model events and Observer methods which the developers can use to hook in the model's lifecycle.

The schedule() method fires two events namely scheduling before saving the model and scheduled after saving the model.

The unschedule() method fires two events namely unscheduling before saving the model and unscheduled after saving the model.

The above events can be caught in the Observer class as follows:

namespace App\Observers;

use App\Post;

class PostObserver
{
    public function scheduling(Post $post)
    {
        //
    }

    public function scheduled(Post $post)
    {
        //
    }

    public function unscheduling(Post $post)
    {
        //
    }

    public function unscheduled(Post $post)
    {
        //
    }
}

4. Fetching data using queries

We will assume below posts table as reference to the following examples:

id title created_at updated_at schedule_at
1 Toy Story 1 2020-06-01 12:15:00 NULL NULL
2 Toy Story 2 2020-08-02 16:10:12 NULL 2020-08-10 10:10:00
3 Toy Story 3 2020-10-10 10:00:10 NULL 2021-12-20 00:00:00
4 Terminator 2 2020-10-11 00:00:00 NULL 2021-11-12 15:10:17

For the following examples, Suppose the current timestamp is 2020-10-18 00:00:00.

1. Default

By default all those models are fetched in which the schedule_at column is having NULL value or a timestamp less than or equal to the current timestamp.

So a eloquent query

$posts = App\Post::get();

will return Toy Story 1 and Toy Story 2

2. Retrieving scheduled models in addition to the normal.

To retrieve scheduled models in addition to the normal models, use the withScheduled() method.

$posts = App\Post::withScheduled()->get();

The above query will return all the four rows in the above table.

3. Retrieving only scheduled models without normal.

To retrieve only scheduled models use the onlyScheduled() method.

$posts = App\Post::onlyScheduled()->get();

The above query will return Toy Story 3 and Terminator 2.

4. Do not apply any functionality provided by Schedulable.

In some cases you may not want to apply the Schedulable trait at all. In those cases use the withoutGlobalScope() method in your query.

use Neelkanth\Laravel\Schedulable\Scopes\SchedulableScope;

$posts = App\Post::withoutGlobalScope(SchedulableScope::class)->get();

A general use case example.

title = "My scheduled post"; $scheduleAt = Carbon\Carbon::now()->addDays(10); $post->schedule($scheduleAt); return $post; //The scheduled post's ID is 1 }); Route::get('/unschedule/post', function () { // To unschedule a post you have to fetch the scheduled post first. // But becuase the Schedulable trait is used in App\Post model it will not a fetch a post whose schedule_at column value is in future. $post = App\Post::find(1); //This will return null for a scheduled post whose id is 1. //To retreive a scheduled post you can use any of the two methods given below. $post = App\Post::withScheduled()->find(1); //1. Using withScheduled() [Recommended] $post = App\Post::withoutGlobalScope(SchedulableScope::class)->find(1); //2. Using withoutGlobalScope() $post->unschedule(); }); ">
// routes/web.php
use Illuminate\Support\Facades\Route;
use Neelkanth\Laravel\Schedulable\Scopes\SchedulableScope;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/schedule/post', function () {
    $post = new App\Post();
    $post->title = "My scheduled post";
    $scheduleAt = Carbon\Carbon::now()->addDays(10);
    $post->schedule($scheduleAt);
    return $post; //The scheduled post's ID is 1
});


Route::get('/unschedule/post', function () {

    // To unschedule a post you have to fetch the scheduled post first.
    // But becuase the Schedulable trait is used in App\Post model it will not a fetch a post whose schedule_at column value is in future.
    
    $post = App\Post::find(1);  //This will return null for a scheduled post whose id is 1.
    
    //To retreive a scheduled post you can use any of the two methods given below.

    $post = App\Post::withScheduled()->find(1); //1. Using withScheduled() [Recommended]

    $post = App\Post::withoutGlobalScope(SchedulableScope::class)->find(1); //2. Using withoutGlobalScope()
    
    $post->unschedule();
});

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Credits

License

MIT

You might also like...
Laravel Cron Scheduling - The ability to run the Laravel task scheduler using different crons

Laravel Cron Scheduling Laravel Task Scheduling is a great way to manage the cron. But the documentation contains the following warning: By default, m

Easily implement optimistic Eloquent model locking feature to your Laravel app.

quarks/laravel-locking Easily implement optimistic Eloquent model locking feature to your Laravel app. Installation composer require quarks/laravel-lo

Modern and simple PHP task runner inspired by Gulp and Rake aimed to automate common tasks

RoboTask Modern and simple PHP task runner inspired by Gulp and Rake aimed to automate common tasks: writing cross-platform scripts processing assets

A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners.

PHP-Queue A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners. Why PHP-Queue? Implementing a

PHP port of resque (Workers and Queueing)

php-resque: PHP Resque Worker (and Enqueue) Resque is a Redis-backed library for creating background jobs, placing those jobs on one or more queues, a

A versatile and lightweight PHP task runner, designed with simplicity in mind.
A versatile and lightweight PHP task runner, designed with simplicity in mind.

Blend A versatile and lightweight PHP task runner, designed with simplicity in mind. Table of Contents About Blend Installation Config Examples API Ch

Manage your Laravel Task Scheduling in a friendly interface and save schedules to the database.
Manage your Laravel Task Scheduling in a friendly interface and save schedules to the database.

Documentation This librarian creates a route(default: /schedule) in your application where it is possible to manage which schedules will be executed a

Crunz is a framework-agnostic package to schedule periodic tasks (cron jobs) in PHP using a fluent API.

Crunz Install a cron job once and for all, manage the rest from the code. Crunz is a framework-agnostic package to schedule periodic tasks (cron jobs)

Manage all your cron jobs without modifying crontab. Handles locking, logging, error emails, and more.

Jobby, a PHP cron job manager Install the master jobby cron job, and it will manage all your offline tasks. Add jobs without modifying crontab. Jobby

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.
Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone. 🚀 Quick start Requires PHP 7.4+ # First, install: c

CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due

PHP Cron Expression Parser NOTE This fork has been deprecated and development moved to https://github.com/dragonmantank/cron-expression. More informat

CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due

The PHP cron expression parser can parse a CRON expression, determine if it is due to run, calculate the next run date of the expression, and calculate the previous run date of the expression. You can calculate dates far into the future or past by skipping n number of matching dates.

Improve default Magento 2 Import / Export features - cron jobs, CSV , XML , JSON , Excel
Improve default Magento 2 Import / Export features - cron jobs, CSV , XML , JSON , Excel

Improve default Magento 2 Import / Export features - cron jobs, CSV , XML , JSON , Excel , mapping of any format, Google Sheet, data and price modification, improved speed and a lot more!

Cron jobs scheduler for Spiral Framework

This is a cron jobs scheduler that can be easily integrated with your project based on spiral framework. The idea was originally inspired by the Laravel Task Scheduling.

An alternative to run cron jobs that uses simple HTTP requests

SilverStripe Simple Jobs An alternative to run cron jobs that uses simple HTTP requests. This module require SilverStripe CronTask. Why? Configuring c

Condor watches diverse statuses, and elegantly reports every drift
Condor watches diverse statuses, and elegantly reports every drift

condor Condor watches diverse statuses, and elegantly reports every drift. Features Uptime: Make sure everything is up and running. Domains: Anticipat

Chain Laravel jobs without having to glue it to a starting job

Laravel Job Chainer JobChainer does chain a variable amount of jobs by adding them with the add() method. This makes it possible to chain jobs without

Tars is a high-performance RPC framework based on name service and Tars protocol, also integrated administration platform, and implemented hosting-service via flexible schedule.

TARS - A Linux Foundation Project TARS Foundation Official Website TARS Project Official Website WeChat Group: TARS01 WeChat Offical Account: TarsClou

Comments
  • Admin : Error 404 on my post when scheduled

    Admin : Error 404 on my post when scheduled

    Hello,

    I'm using your awesome library to schedule posts on my blog, however I'm stuck on the admin side. I have scheduled posts and unscheduled posts (published or drafted), but when I'm trying to edit a scheduled post it returns 404, which is the the way your package works.

    Is there a way to bypass your usual Trait behaviour on the route side ? Maybe say to this route specifically to ignore the schedule trait, because I can't get it done on controller side.

    I'm open to suggestions to try to figure this one out.

    Have a nice day.

    opened by ABCrafty 2
  • Suggestion / Note

    Suggestion / Note

    Hi, Thanks for this awesome package. I have a note regarding Model records fetching, I think it's a wrong idea to affect the standard query which get all rows. The best / correct way to use the package :

    $posts = App\Post::get(); // keep the standard method to get all records
    $posts = App\Post::expiredScheduled()->get(); // to get expired scheduled records
    $posts = App\Post::nextScheduled()->get(); // to get future scheduled records
    

    Thanks.

    opened by AEK-BKF 1
  • how can i schedule delete and update a column field?

    how can i schedule delete and update a column field?

    Assume you have E-commerce site probably you will want to schedule deletion an updation of discount table how can I perform that by using this package.

    opened by nitunga 0
Releases(1.1.0)
Owner
Neelkanth Kaushik
Software Engineer and Application Architect. Student for lifetime.
Neelkanth Kaushik
Manage all your cron jobs without modifying crontab. Handles locking, logging, error emails, and more.

Jobby, a PHP cron job manager Install the master jobby cron job, and it will manage all your offline tasks. Add jobs without modifying crontab. Jobby

null 1k Dec 25, 2022
A course database lookup tool and schedule building web application for use at Rochester Institute of Technology.

CSH ScheduleMaker A course database lookup tool and schedule building web application for use at Rochester Institute of Technology. Built, maintained

Computer Science House 55 Nov 8, 2022
xcron - the souped up, modernized cron/Task Scheduler for Windows, Mac OSX, Linux, and FreeBSD server and desktop operating systems.

xcron is the souped up, modernized cron/Task Scheduler for Windows, Mac OSX, Linux, and FreeBSD server and desktop operating systems. MIT or LGPL.

CubicleSoft 7 Nov 30, 2022
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

Indatus 1.1k Jan 5, 2023
Manage Your Laravel Schedule From A Web Dashboard

Introduction Manage your Laravel Schedule from a pretty dashboard. Schedule your Laravel Console Commands to your liking. Enable/Disable scheduled tas

ⓒⓞⓓⓔ ⓢⓣⓤⓓⓘⓞ 1.6k Jan 5, 2023
Manage Your Laravel Schedule From A Web Dashboard

Introduction Manage your Laravel Schedule from a pretty dashboard. Schedule your Laravel Console Commands to your liking. Enable/Disable scheduled tas

ⓒⓞⓓⓔ ⓢⓣⓤⓓⓘⓞ 1.6k Jan 1, 2023
PHP cron job scheduler

PHP Cron Scheduler This is a framework agnostic cron jobs scheduler that can be easily integrated with your project or run as a standalone command sch

Giuseppe Occhipinti 698 Jan 1, 2023
Cron expression generator built on php8

The most powerful and extendable tool for Cron expression generation Cron expression generator is a beautiful tool for PHP applications. Of course, th

Pavel Buchnev 46 Nov 27, 2022
Task Scheduling with Cron Job in Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Shariful Islam 1 Oct 16, 2021
Cron Job Manager for Magento 2

EthanYehuda_CronJobManager A Cron Job Management and Scheduling tool for Magento 2 Control Your Cron Installation In your Magento2 root directory, you

Ethan Yehuda 265 Nov 24, 2022