daycry/cronjob

Cronjob library for Codeigniter 4

Installs: 23 827

Dependents: 3

Suggesters: 0

Security: 0

Stars: 65

Watchers: 4

Forks: 20

Open Issues: 0

Language:JavaScript

v2.2.29 2024-08-12 12:40 UTC

README

Donate

Note

If you want to use a queue system you can use queues vendor

CodeIgniter Task Scheduler

Build Status Coverage Status Downloads GitHub release (latest by date) GitHub stars GitHub license

This makes scheduling cronjobs in your application simple, flexible, and powerful. Instead of setting up multiple cronjobs on each server your application runs on, you only need to setup a single cronjob to point to the script, and then all of your tasks are scheduled in your code. Besides that, it provides CLI tools to help you manage the tasks that should be ran, a Debug Toolbar collector, and more.

Installation via composer

Use the package with composer install

> composer require daycry/cronjob

Configuration

Run command:

> php spark cronjob:publish

This command will copy a config file to your app namespace. Then you can adjust it to your needs. By default file will be present in app/Config/CronJob.php.

> php spark migrate -all

This command create rest server tables in your database.

Starting the Scheduler

You only need to add a single line to your cronjob:

> * * * * * php /path-to-your-project/spark cronjob:run >> /dev/null 2>&1

This will call your script every minute. When cronjob:run is called, Tasks will determine the correct tasks that should be run and execute them.

Dashboard

You can access the web interface to view the status of jobs using the following url: https://example.com/cronjob You must configure an username and password in CronJob.php Config file.

    /*
    |--------------------------------------------------------------------------
    | Dashboard login
    |--------------------------------------------------------------------------
    */
    public string $username = 'admin';
    public string $password = 'admin';

Custom Views

Go to app\Config\CronJob.php ->views['dashboard'] and put your view's path there, like: "Cronjob/dashboard" - which is located in app\Views\Cronjob\dashboard.php

/*
    |--------------------------------------------------------------------------
    | Views
    |--------------------------------------------------------------------------
    |
    | Notification of each task
    |
    */
    public array $views = [
        'login'                       => '\Daycry\CronJob\Views\login',
        'dashboard'                   => '\Daycry\CronJob\Views\dashboard',
        'layout'                      => '\Daycry\CronJob\Views\layout',
        'logs'                        => '\Daycry\CronJob\Views\logs'
    ];

CronJob List

Defining Schedules

Tasks are configured with the app/Config/CronJob.php config file, inside of the init() method. Lets start with a simple example:

<?php namespace Daycry\CronJob\Config;

use CodeIgniter\Config\BaseConfig;
use Daycry\CronJob\Scheduler;

class CronJob extends BaseConfig
{
    /*
    |--------------------------------------------------------------------------
	| Cronjobs
	|--------------------------------------------------------------------------
    |
	| Register any tasks within this method for the application.
	| Called by the TaskRunner.
	|
	| @param Scheduler $schedule
	*/
    public function init(Scheduler $schedule)
    {
        $schedule->call(function() { 
            DemoContent::refresh();
        })->everyMonday();
    }
}

In this example, we use a closure to refresh demo content at 12:00 am every Monday morning. Closures are a simple way to handle quick functions like this. You can also execute server commands, execute custom CLI commands you have written, call a URL, or even fire off an Event of your choosing. Details are covered below.

Scheduling CLI Commands

If you have written your own CLI Commands, you can schedule them to run using the command() method.

$schedule->command('demo:refresh --all');

The only argument is a string that calls the command, complete with an options or arguments.

Scheduling Shell Commands

You can call out to the server and execute a command using the shell() method.

$schedule->shell('cp foo bar')->daily( '11:00 pm' );
$schedule->shell('cp foo bar')->daily( '23:00' );

Simply provide the command to call and any arguments, and it will be executed using PHP's exec() method.

NOTE: Many shared servers turn off exec access for security reasons. If you will be running on a shared server, double-check you can use the exec command before using this feature.

Scheduling Events

If you want to trigger an Event you can use the event() method to do that for you, passing in the name of the event to trigger.

$schedule->event('Foo')->hourly();

Running Command In Background

If you want to run a command in background, you can use the runInBackground() method to do that for you, so the command won't block the execution of the next schedulers.

Note

Currently only commands are able to run in background

$schedule->command('slow-command')->runInBackground()->hourly();

It prevents the command from blocking the execution of the next schedulers.

Running On One server

If your scheduler runs on multiple servers, you can determine if your scheduled job will executes in a single or in multiple servers using the setRunType method.

Note

By default, the scheduled job will execute in multiple servers

$schedule->event('Foo')->setRunType('multiple')->hourly(); // Runs in all servers
$schedule->event('Foo')->setRunType('single')->hourly(); // Runs in one server

This prevents duplication of tasks across servers by securing a lock on the job, ensuring it runs exclusively on the first server that obtains it.

Scheduling URL Calls

If you need to ping a URL on a regular basis, you can use the url() method to perform a simple GET request using cURL to the URL you pass in. If you need more dynamism than can be provided in a simple URL string, you can use a closure or command instead.

$schedule->url('https://my-status-cloud.com?site=foo.com')->everyFiveMinutes();

Frequency Options

There are a number of ways available to specify how often the task is called.

These methods can be combined to create even more nuanced timings:

$schdule->command('foo)
    ->weekdays()
    ->hourly()
    ->environments('development');

Naming Tasks

You can name tasks so they can be easily referenced later, such as through the CLI with the named() method:

$schedule->command('foo')->hourly()->named('foo-task');

CLI Commands

Included in the package are several commands that can be ran from that CLI that provide that bit of emergency help you might need when something is going wrong with a cron job at a specific time.

All commands are ran through CodeIgniter's spark cli tool:

> php spark cronjob:list
> php spark cronjob:run
> php spark cronjob:run -testTime "2021-01-01 09:45:00"

Or if you prefer, you can run one or more specific jobs by passing the names separated by commas

> php spark cronjob:run -only "foo-task,foo-task1"

Available Commands

cronjob:list

> php spark cronjob:list

This will list all available tasks that have been defined in the project, along with their type and the next time they are scheduled to run.

+--------------------------+---------+-------------+---------------------+---------------------+
| Name                     | Type    | Expression  | Last Run            | Next Run            |
+--------------------------+---------+-------------+---------------------+---------------------+
| job1                     | command | 08 10 * * * | --                  | 2022-11-04 10:08:00 |
| Job2                     | command | 0 0 * * *   | 2022-10-28 13:23:21 | 2022-11-05 00:00:00 |
+--------------------------+---------+-------------+---------------------+---------------------+

cronjob:disable

> php spark cronjob:disable 

Will disable the task runner manually until you enable it again. Writes a file to {WRITEPATH}/cronJob so you need to ensure that directory is writable. Default CodeIgniter permissions already have the WRITEABLE path with write permissions. You should not need to change anything for this to work.

cronjob:enable

> php spark cronjob:enable

Will enable the task runner if it was previously disabled, allowing all tasks to resume running.

cronjob:run

> php spark cronjob:run

This is the primary entry point to the Tasks system. It should be called by a cron task on the server every minute in order to be able to effectively run all of the scheduled tasks. You typically will not run this manually.

Notifications

If you want to receive notifications by email, simply configure the Codeigniter Email library.