Select Page

PHP sleep2next function

I had a project done for a client, where I needed a code to run again every second, since cron-tabs work every minute I use an inner function to keep the code running.

I did it for them before, I used the simple sleep function, but this code needed a more precise timing, i can’t miss a second of data.

So I came up with a simple function that solves it:

function sleep2next() {
  usleep( intval( ( ( time() + 1 ) - microtime(true) ) * 1000000 ) );
}

The code calculates the miliseconds until next round second and pauses the code for that period of time,  the further code will now start as soon as possible after the next second.

Notice: on windows platforms it might act somewhat strange.