Giter VIP home page Giter VIP logo

laravel-database-schedule's Introduction

Laravel Database Schedule

Documentation

This librarian creates a route(default: /schedule) in your application where it is possible to manage which schedules will be executed at any given moment, these schedules are recorded in the database and can be changed, activated, inactivated or deleted via the interface without the need for a new application deployment.

List Schedules

Create Schedules

Show History Schedules

Installation

  1. Run composer require robersonfaria/laravel-database-schedule
  2. Run php artisan migrate

Environment variables

You can set the following environment variables to configure schedules:

  • SCHEDULE_TIMEZONE : The default is the same configured for the application, but if you need the schedules to run in a different timezone, it is possible to configure it with this variable
  • SCHEDULE_CACHE_DRIVER : The default is file
  • SCHEDULE_CACHE_ENABLE : The default is disabled when APP_DEBUG=true and enabled when APP_DEBUG=false

Configurations

There are several library configuration options, to change the settings you can get the configuration file for your project

php artisan vendor:publish --provider="RobersonFaria\DatabaseSchedule\DatabaseSchedulingServiceProvider" --tag="config"

Dashboard Authorization

Dashboard Authorization exposes a dashboard at /schedule URI.

In the configuration file it is possible to define whether to restrict access to route /schedule, the default is true. If access is restricted, the user must be logged in and meet the requirements defined in the viewDatabaseSchedule gate controls access.

<?php
return [
    //...
    /**
     * If restricted_access is true, the user must be authenticated and meet the definition of `viewDatabaseSchedule` gate
     */
    'restricted_access' => env('SCHEDULE_RESTRICTED_ACCESS', true),
    //...
]

Note that this value can also be changed using the SCHEDULE_RESTRICTED_ACCESS environment variable.

ATTENTION: if restricted_access is set to false, access to the / schedule route will be public.

You must define the gates in your service providers, laravel by default already brings the provider App\Providers\AuthServiceProvider for this purpose. See more in the Laravel documentation https://laravel.com/docs/8.x/authorization#gates

You are free to modify this gate as needed to restrict access to your Database Schedule Dashboard.

protected function gate()
{
    Gate::define('viewDatabaseSchedule', function ($user) {
        return in_array($user->email, [
            '[email protected]',
        ]);
    });
}

Examples:

If you want to limit access to a route to users who have a certain role, you can do so.

Gate::define('viewDatabaseSchedule', function ($user) {
     return $user->hasRole('administrator');
});

Basically, if your gate has return true access will be allowed, if return false access will be restricted.

Groups:

If you have a lot of jobs, you can make managing them easier by enabling the groups feature in config/database-schedule.php:

    /**
     * If you have a lot of jobs, you can group them for easier managing of jobs.
     */
    'enable_groups' => true,

This will allow you to filter in the job listing only the jobs belonging to a certain group.

Scheduled Task Example

Create the command for your scheduled task app/Console/Commands/test.php:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:test {user} {initialDate} {finalDate}';

    /**
     * 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 int
     */
    public function handle()
    {
        $this->info('Hello ' . $this->argument('user'));
        $this->info("Initial Date: " . $this->argument('initialDate'));
        $this->info("Final Date: " . $this->argument('finalDate'));
        return 0;
    }
}

Access the dashboard and the command will be listed for scheduling, create a schedule like the example below: Create Schedule

Run the artisan command to run scheduled tasks

php artisan schedule:run

The console output will look like this

Running scheduled command: ('/usr/bin/php7.4' 'artisan' command:test 1 '2022-02-02 00:00:00' '2022-04-02 00:00:00' > 'path/to/storage/logs/schedule-8763d2ce5a20ee888dd9d8a7e5a5cfcd4b315375.log' 2>&1 ;

If you marked the sending of the output by email you will receive an email similar to this one:

Mail Output

Schedule List

You can also list registered and active commands using artisan command:

$ php artisan schedule:list

+----------------------------------------------------------------------------------------+-----------+-------------+----------------------------+
| Command                                                                                | Interval  | Description | Next Due                   |
+----------------------------------------------------------------------------------------+-----------+-------------+----------------------------+
| '/usr/bin/php7.4' 'artisan' inspire                                                    | * * * * * |             | 2022-03-02 17:05:00 +00:00 |
| '/usr/bin/php7.4' 'artisan' command:test 1 '2022-02-02 00:00:00' '2022-04-02 00:00:00' | * * * * * |             | 2022-03-02 17:05:00 +00:00 |
+----------------------------------------------------------------------------------------+-----------+-------------+----------------------------+

CHANGELOG

CHANGELOG.md

Credits

laravel-database-schedule's People

Contributors

andreypopov avatar hasanatcc avatar laravel-shift avatar pedropms avatar robersonfaria avatar skarjoss avatar thyseus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

laravel-database-schedule's Issues

Unable to install package on laravel 11 project.

when adding package using composer getting this error, even after doing some tweaks of database migration.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'schedule_task_laravel.schedules' doesn't exist (Connection: mysql, SQL: select * from schedules where status = 1 and schedules.deleted_at is null)

at vendor\laravel\framework\src\Illuminate\Database\Connection.php:813
809▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
810▕ );
811▕ }
812▕
➜ 813▕ throw new QueryException(
814▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
815▕ );
816▕ }
817▕ }

i A table was not found: You might have forgotten to run your database migrations.
https://laravel.com/docs/master/migrations#running-migrations

1 [internal]:0
RobersonFaria\DatabaseSchedule\Console\Scheduling\Schedule::__construct(Object(RobersonFaria\DatabaseSchedule\Http\Services\ScheduleService), Object(Illuminate\Console\Scheduling\Schedule))

2 vendor\laravel\framework\src\Illuminate\Database\Connection.php:407
PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146 Table 'schedule_task_laravel.schedules' doesn't exist")

Update Readme to help out new folk

Hey,

It would be great if you could add an example of how to modify the gate in the Dashboard Authorization section

It's a crucial part of the install and not all users will be familiar with extending vendor Service Providers 👍

`schedule:list` shows no configured schedules

Hi, i am using the very most recent laravel version v8.41.0 and unfortunately after installing robersonfaria/laravel-database-schedule the artisan schedule:list command is always returning nothing, regardless of what i configure in the backend:

grafik

# php artisan schedule:list
+---------+----------+-------------+----------+
| Command | Interval | Description | Next Due |
+---------+----------+-------------+----------+
#

When removing robersonfaria/laravel-database-schedule again, the command displays the tasks defined in App\Console\Kernel.php again as it should. I know this once worked ! Possibly laravel/framework has changed something in recent versions? Can i provide any more debug information ? Or did i forget to register the module somewhere? I am out of clues. Thanks a lot !

In case of failure, duplicate emails are sent

When selecting to send email on success and failure, when a command fails, duplicate email is sent. I still haven't found a solution to the problem, apparently it's a behavior of the framework.

Case also interests @PedroPMS

Add PHP 8 support

Hi, please add PHP 8 support

robersonfaria/laravel-database-schedule[1.0.0, ..., 1.0.15] require php ^7.0 -> your php version (8.0.0) does not satisfy that requirement.

not able to change Timezone

Hi, i am using this package and the documentation of this package says i can change timezone with the config file. I have tried but timezone is not picking value from package configuration file (SCHEDULE_TIMEZONE ).

Also i want to put timezone according to user. is there a way to pass timezone in the $schedule array when creating new schedule?

Thankyou

Translation not working

Hello.

I'm trying translate the UI to portuguese creating a file like schedule.php in my resources/lang/pt_BR folder, and this is not working. If I go to your package folder in vendor and add a pt_BR folder with my translations, it works.

Anyway, I forked the project to add the pt_BR folder directly to your project and already do the translations. I'm sending the PR, this can help those who have projects in pt_BR

Creation of new tests (PHPUnit)

The package is growing fast and new features are being added constantly, we need to write tests(PHPUnit) to cover most of the features.
It's becoming more and more difficult to test and ensure that everything keeps working after a new pull request.

Laravel 11 support

[UPDATED]

Version

### PHP VERSION:
8.3.4

### PHP EXTENSIONS:
Core, date, libxml, openssl, pcre, zlib, filter, hash, json, pcntl, random, Reflection, SPL, session, standard, sodium, mysqlnd, PDO, xml, bcmath, calendar, ctype, curl, dom, mbstring, FFI, fileinfo, ftp, gd, gettext, iconv, igbinary, imagick, imap, intl, ldap, exif, msgpack, mysqli, pcov, pdo_mysql, pdo_pgsql, pdo_sqlite, pgsql, Phar, posix, readline, redis, shmop, SimpleXML, soap, sockets, sqlite3, sysvmsg, sysvsem, sysvshm, tokenizer, xmlreader, xmlwriter, xsl, zip, memcached, swoole, Zend OPcache, xdebug

### LARAVEL VERSION:
11.2.0.0

Reproduce the error

  1. Create a new Laravel project
  2. composer require robersonfaria/laravel-database-schedule
./composer.json has been updated
Running composer update robersonfaria/laravel-database-schedule
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
  - Locking robersonfaria/laravel-database-schedule (1.4.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Downloading robersonfaria/laravel-database-schedule (1.4.0)
  - Installing robersonfaria/laravel-database-schedule (1.4.0): Extracting archive
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

   Illuminate\Database\QueryException 

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'agilts_backend.schedules' doesn't exist (Connection: mysql, SQL: select * from `schedules` where `status` = 1 and `schedules`.`deleted_at` is null)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:813
    809▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    810▕                 );
    811▕             }
    812▕ 
  ➜ 813▕             throw new QueryException(
    814▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    815▕             );
    816▕         }
    817▕     }

  i   A table was not found: You might have forgotten to run your database migrations. 
      https://laravel.com/docs/master/migrations#running-migrations

  1   [internal]:0
      RobersonFaria\DatabaseSchedule\Console\Scheduling\Schedule::__construct()
      +13 vendor frames 

  15  [internal]:0
      RobersonFaria\DatabaseSchedule\Console\Scheduling\Schedule::__construct()

Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1
  1. php artisan migrate
   Illuminate\Database\QueryException 

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'agilts_backend.schedules' doesn't exist (Connection: mysql, SQL: select * from `schedules` where `status` = 1 and `schedules`.`deleted_at` is null)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:813
    809▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    810▕                 );
    811▕             }
    812▕ 
  ➜ 813▕             throw new QueryException(
    814▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    815▕             );
    816▕         }
    817▕     }

  i   A table was not found: You might have forgotten to run your database migrations. 
      https://laravel.com/docs/master/migrations#running-migrations

  1   [internal]:0
      RobersonFaria\DatabaseSchedule\Console\Scheduling\Schedule::__construct()
      +13 vendor frames 

  15  [internal]:0
      RobersonFaria\DatabaseSchedule\Console\Scheduling\Schedule::__construct()

Temporary solution

In vendor/robersonfaria/laravel-database-schedule/src/DatabaseSchedulingServiceProvider.php file

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
    ...
//        Comment this line when initializing the project
//        $this->app->resolving(BaseSchedule::class, function ($schedule) {
//            $schedule = app(Schedule::class, ['schedule' => $schedule]);
//            return $schedule->execute();
//        });
    ...
    }

Problem in request to create a schedule

Hello,

I have a command that have two arguments, I want to create a schedule passing just the first, but the request is sending all, like the image shows.
Because of this, when cron runs, the method in Schedule model mapArguments break. I can resolve this is backend but I think is also a problem in the frontend that send invalid data.

I could resolve this too, but I'm terrible at frontend 😅.

image

Command parameters with comments are not recognized

Hi,

at first - thanks a lot for this great repository.

Unfortunately Commands that have Arguments with a comment are not recognized by laravel-database-schedule. Take this Example of the official telescope module:

class PruneCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'telescope:prune {--hours=24 : The number of hours to retain Telescope data}';

The argument --hours is not recognized and therefore can not be set:

grafik

The parameters are collected in src/Http/Services/CommandService.php but unfortunately i can not grasp why
$command->getDefinition()->getArguments()) in line 31 does not retrieve commented arguments. Possibly this is a laravel issue ?

Besides of that, how about an switch to enter a completely custom command as text field in addition to the dropdown for some special cases?

Setting verbosity not possible?

Hi, this might be a really stupid question, but I cannot seem to find a way to specify the verbosity. There is neither a dropdown nor a generic input where I could specify additional parameters like "-vv".
Good logging is pretty important for my use case.

Duplicate output when send mail

When you put an email to receive the output of the scheduled command, this out put is registred an sended twice.

image

To reproduce the error, run the command without send mail option, after that register an email in the command and run it again.

Add a button to run the scheduled job "now"

Could there be a possibility to add "run now" button on every job, so one does not need to wait for the crontab to proc and instead run some, especially maintenance tasks on demand?

Thanks

Update documentation

Various modifications and additions of new functionality have been made, it is necessary to update the documentation(README) to reflect all existing functionality.

If anyone can contribute I appreciate it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.