'How to create a scheduler application in php

I want to develop a scheduler in php I know there is cronjob already present in php but I want to develop like java but I don't want to use sleep(1) method. I know how to develop it in JAVA. JAVA code is given below.

scheduler = schedulerFactory.getScheduler();
            JobDetail job = JobBuilder.newJob(GenerateJob.class).build();

            SimpleTrigger simpletrigger = (SimpleTrigger) TriggerBuilder.newTrigger().startAt(startTime)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withIntervalInHours(Integer.parseInt(Constants.INTERVAL_HOUR)).repeatForever())
                    .build();

            scheduler.scheduleJob(job, simpletrigger);
            scheduler.start();

AND

public class GenerateJob implements Job {

     // Operation will be placed here

}

Is it possible to develop like above in php? If not then is there any way to develop scheduler. Help me with code. Thanks in advance.



Solution 1:[1]

You can try this Quartz. Here are some examples as well. Its similar implementation for the scheduler in PHP as you are looking for.

Solution 2:[2]

In my case, I need to run scripts every 1, 5 and 30 seconds but independent of platform (must work either on Windows and Linux platforms) with same source code. So I made the following, which is executing in about 15 microseconds every second. Very quick !

// init priorities array in seconds
$schedules = [
    'high'  => 1,
    'medium'=> 5,
    'low'   => 30
];

while($now ??= time()) {
    foreach($schedules as $priority => $seconds)  {
        if($now >= $next[$priority] ??= $now) {
            $next[$priority] += $seconds;
            
            // --> execute your script here for every priority
            // in my case I call high.php, medium.php and low.php with 
            // with execInBackground() by TheUO available here : 
            // https://stackoverflow.com/a/12117258/2282880;
            
            // something like execInBackground("scripts/", "$priority.php");
        }
    }
    time_sleep_until(++$now);
}

working since PHP 7.4 (especially for ??=)

Hope it could help some of you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajat Arora
Solution 2 Meloman