PHP code example of philippgrashoff / cronforatk

1. Go to this page and download the library: Download philippgrashoff/cronforatk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

philippgrashoff / cronforatk example snippets


$persistence = new Sql(
    'connection_string',
    'username',
    'password'
);

//Setup database
$scheduler = new Scheduler($this->db);
(new Migrator($scheduler))->create();
$executionLog = new ExecutionLog($this->db);
(new Migrator($executionLog))->create()->createForeignKey($executionLog->getReference('scheduler_id'));

class MyCronJob extends BaseCronJob
{

    public static string $name = 'SomeNameForThisCron';
    public static string $description = 'SomeDescriptionExplainingWhatThisIsDoing';

    public bool $strict = false;

    public function execute(): void
    {
        //do something
        $someModel = new SomeModel($this->persistence);
        $someModel->setLimit(100);
        foreach ($someModel as $entity) {
            if($this->strict) {
                $entity->doSomeStrictCheck();
            }
            else {
                $entity->doSomeOtherCheck();
            }
            //optionally add some output to log
            $this->executionLog[] = 'SomeModel With ID ' . $entity->getId()
                . 'checked at ' . (new \DateTime())->format(DATE_ATOM);
        }
    }
}

//tell the Schedulers where to look for Cronjob implementations.
//In real implementations, extend Scheduler to set this once for all Schedulers
$pathsToCronJobs = [__DIR__ => 'cronforatk\docs'];

//Have our Cronjob executed Daily.
$schedulerDaily = new Scheduler($persistence, ['cronFilesPaths' => $pathsToCronJobs]);
$schedulerDaily->set('cronjob_class', MyCronJob::class);
$schedulerDaily->set('interval', 'DAILY');
$schedulerDaily->set('time_daily', '03:45');
$schedulerDaily->save();

//you could add more schedulers executing the same cronjob in different intervals.
// Here, we will add a weekly check sets the "strict" of MyCronJob to true. Like this, cronjobs can be parametrized
$schedulerWeekly = new Scheduler($persistence, ['cronFilesPaths' => $pathsToCronJobs]);
$schedulerWeekly->set('cronjob_class', MyCronJob::class);
$schedulerWeekly->set('interval', 'WEEKLY');
$schedulerWeekly->set('weekday_weekly', 6); //Saturday
$schedulerWeekly->set('time_weekly', '01:32');
$schedulerWeekly->set('defaults', ['strict' => true]);
$schedulerWeekly->save();

$executor = new Executor($persistence);
$executor->run();