peppeocchi / php-cron-scheduler

PHP cron job scheduler
MIT License
811 stars 144 forks source link

work() cpu 100% #131

Closed okool closed 2 years ago

okool commented 2 years ago
public function work(array $seconds = [0])
    {
        while (true) {
            if (in_array((int) date('s'), $seconds)) {
                $this->run();
                sleep(1);
            }
        }
    }

to

public function work(array $seconds = [0])
    {
        while (true) {
            if (in_array((int) date('s'), $seconds)) {
                $this->run();
            }
           sleep(1);
        }
    }
peppeocchi commented 2 years ago

It's a good suggestion but it might miss runs. This is not intended for a production environment, but only for testing the scheduler is working.

What I mean by missing runs is easy to explain. Your version will sleep for 1 second on every loop, but there is also some overhead on running those 4 lines of code, so your entire execution will take 1 second and 50 milliseconds. In the long run all those milliseconds add up to a second, so let's say your next loop enters at 00:00:59.980. then you sleep for 1 second plus the overhead of 50 milliseconds, the next run will be at 00:01:01.030. If you want it to run at second 0, that run will be missed, because on the previous run date('s') = 59, on the current run date('s') = 1.

A more optimised (?) version might be to usleep for the amount of ms left in your second. If you want to do it, please fell free to create a PR, thanks

cuchac commented 1 year ago

Hello, we currently face the same issue. We had to reimplement the work loop in our application, because we just called work() from the library and did not care about implementation and we were surprised to discover 100% CPU load.

Would you accept PR implementing following logic? 1) Find earliest schedule date from all jobs 2) Sleep using usleep() exact number of ms 3) $this->run(); 4) Repeat