Scheduling Tasks in PHP

by|Oct 19, 2022

In the scenario where you want to execute tasks repeatedly at a specific time and have full control over when they are executed and how the results are handled, it makes sense to build this into your application instead of setting up a cron job, for example. I’d like to give you a quick example of how you can achieve this in PHP using two great libraries,ReactPHPandcron-expression. ReactPHP is an event-driven programming library that has an event loop at its core. cron-expression understands CRON expressions, can determine if they are due to be executed and calculate the next execution date of the expression. The following is a simple example of scheduling tasks based on these two libraries:

isDue($now)) { Loop::futureTick(function () use ($task) { $task(); }); } // Function that executes the task // and adds a timer to the event loop to execute the function again when the task is next due: $schedule = function () use (&$schedule, $task, $cron) { $task(); $now = new DateTime(); $nextDue = $cron->getNextRunDate($now); Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $schedule); }; // Add a timer to the event loop to execute the task when it is next due: $nextDue = $cron->getNextRunDate($now); Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $schedule); } // Run example task every minute: $cron = new CronExpression('* * * * *'); $task = function () { echo date('Y-m-d H:i:s') . ": Task running\n"; }; schedule($task, $cron);

你也可以Like…

Icinga Camp Milan 2023

It’s time to spread some monitoring love! We’re super happy to announce our next Icinga Camp in Milan, on October 17th, 2023

Icinga Kubernetes Helm Charts

Before attending Icinga Berlin in May this year, Daniel Bodky and Markus Opolka from our partner NETWAYS developed the...

IPL:如何使用ipl-validator

In my last blogpost I explained how our ipl-html lib works and how to use it. With the help of ipl-html it is possible...

Subscribe to our Newsletter

A monthly digest of the latest Icinga news, releases, articles and community topics.