Giter Site home page Giter Site logo

msmakouz / scheduler Goto Github PK

View Code? Open in Web Editor NEW

This project forked from spiral-packages/scheduler

0.0 0.0 0.0 84 KB

The scheduler is a package for spiral framework. It will help to managing scheduled tasks on your server.

Home Page: https://spiral.dev/docs/packages-scheduler

License: MIT License

PHP 100.00%

scheduler's Introduction

Cron jobs scheduler for Spiral Framework

PHP Latest Version on Packagist GitHub Tests Action Status Total Downloads

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.

Requirements

Make sure that your server is configured with following PHP version and extensions:

  • PHP 8.1+
  • Spiral framework 3.0+

Installation

You can install the package via composer:

composer require spiral-packages/scheduler

After package install you need to add bootloader from the package to your application.

use Spiral\Scheduler\Bootloader\SchedulerBootloader;

protected const LOAD = [
    // ...
    SchedulerBootloader::class,
];

At first you need to create config file app/config/scheduler.php

<?php

declare(strict_types=1);

$generator = \Butschster\CronExpression\Generator::create();

return [
    'queueConnection' => env('SCHEDULER_QUEUE_CONNECTION', 'sync'),
    'cacheStorage' => env('SCHEDULER_CACHE_STORAGE', 'redis'), // for mutexes
    'timezone' => 'UTC',
    'expression' => [
        'aliases' => [
            '@everyFiveMinutes' => (string)$generator->everyFiveMinutes(),
            '@everyFifteenMinutes' => (string)$generator->everyFifteenMinutes(),
        ],
    ],
];

Add a cron configuration entry to our server that runs the schedule:run command every minute.

* * * * * cd /path-to-your-project && php app.php schedule:run >> /dev/null 2>&1

If you don't have crontab or you want to run schedule via RoadRunner, you may use the schedule:work command.This command will run in the foreground and invoke the scheduler every minute until you terminate the command:

php app.php schedule:work

Or via RoadRunner

service:
  cron_worker:
    command: "php app.php schedule:work"
    process_num: 1
    exec_timeout: 0
    remain_after_exit: true
    restart_sec: 1

Read more about RoadRunner configuration in the official documentation

Usage

Create a new bootloader, for example, SchedulerBootloader in your application

use Spiral\Boot\Bootloader\Bootloader;
use App\Scheduling\Schedule;
use Psr\Log\LoggerInterface;

final class SchedulerBootloader extends Bootloader
{
    public function boot(Schedule $schedule): void
    {
        // Run command by name
        $schedule->command('ping', ['https://google.com'])
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->appendOutputTo(directory('runtime').'logs/cron.log');
            
        // Run command by class
        $schedule->command(Command\PingCommand::class, ['https://google.com'])
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->appendOutputTo(directory('runtime').'logs/cron.log');
            
        // Run callable command
        $schedule->call('Ping url', static function (LoggerInterface $logger, string $url) {
            $headers = @get_headers($url);
            $status = $headers && strpos($headers[0], '200');

            $logger->info(sprintf('URL: %s %s', $url, $status ? 'Exists' : 'Does not exist'));

            return $status;
        }, ['url' => 'https://google.com'])->everyFiveMinutes()->withoutOverlapping();
    }
}

You can also register scheduler jobs via PHP attributes

use Spiral\Scheduler\Attribute\Schedule;

#[Schedule(
    expression: '@everyFiveMinutes',
    name: 'Ping url', 
    parameters: ['url' => 'https://google.com'],
    withoutOverlapping: true,
    runAs: 'root',
    runInBackground: true
)]
class SimpleJob
{
    public function __construct(
        private LoggerInterface $logger
    )  {
        
    }
    
    public function run(LoggerInterface $logger, string $url)
    {
        $headers = @get_headers($url);
        $status = $headers && \strpos($headers[0], '200');

        $this->logger->info(\sprintf('URL: %s %s', $url, $status ? 'Exists' : 'Does not exist'));
    }
}

Testing

composer test

If you are using spiral/testing package in your application, you can additionally use trait Spiral\Scheduler\Testing\InteractsWithSchedule in your tests cases.

class MyJobSchedulingTest extends TestCase
{
    use \Spiral\Scheduler\Testing\InteractsWithSchedule;

    public function testCheckIfJobRun(): void
    {
        $scheduler = $this->runScheduler('*/15 * * * *');
        
        $scheduler->assertHandled(function (\Spiral\Scheduler\Job\Job $job) {
            return $job->getName() === 'My super job';
        });
        
        $scheduler->assertHandledTotalJobs(5);
    }
}

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

scheduler's People

Contributors

butschster avatar dependabot[bot] avatar msmakouz avatar

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.