PHP code example of aleblanc / simple-cron-scheduler

1. Go to this page and download the library: Download aleblanc/simple-cron-scheduler 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/ */

    

aleblanc / simple-cron-scheduler example snippets


use SimpleCronScheduler\Attribute\AsCronTask;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;

#[AsCommand(name: 'app:sync-feed')]
#[AsCronTask('*/2 * * * *', between: ['7:00', '22:00'], skipMinutes: [2, 32], description: 'Daytime sync')]
#[AsCronTask('*/15 * * * *', unlessBetween: ['7:00', '22:00'], skipMinutes: [2, 32], description: 'Nighttime sync')]
#[AsCronTask('@daily', args: ['--full'], env: ['prod'])]
// Hourly, weekdays only (Mon–Fri), but never between midnight and 6am, never in December:
#[AsCronTask('0 * * * *', days: [1, 2, 3, 4, 5], skipHours: [0, 1, 2, 3, 4, 5], skipMonths: [12])]
final class SyncFeedCommand extends Command { /* ... */ }

namespace App\Cron;

use SimpleCronScheduler\Condition\CronCondition;

final class NotPublicHoliday implements CronCondition
{
    public function isAllowed(\DateTimeImmutable $now): bool
    {
        return !$this->holidays->contains($now);
    }
}

#[AsCronTask('0 9 * * 1-5', when: \App\Cron\NotPublicHoliday::class)]

use SimpleCronScheduler\Event\TaskFailedEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
final class MailOnTaskFailure
{
    public function __construct(private MailerInterface $mailer) {}

    public function __invoke(TaskFailedEvent $event): void
    {
        $this->mailer->send((new Email())
            ->to('[email protected]')
            ->subject(sprintf('[cron] %s failed (exit %d)', $event->task->name, $event->result->exitCode))
            ->text($event->result->output));
    }
}