@@ -194,19 +194,30 @@ public static function isInteractive(): bool
194194 }
195195
196196 /**
197- * @param callable $callback
198- * @param float $sleep // in seconds!
199- * @param callable $onError
197+ * @param callable $callback
198+ * @param int $sleep // in seconds!
199+ * @param int $delay // in seconds!
200+ * @param callable|null $onError
201+ * @throws \Exception
200202 */
201- public static function loop (callable $ callback , $ sleep = 1 /* seconds */ , callable $ onError = null ): void
203+ public static function loop (callable $ callback , int $ sleep = 1 /* seconds */ , int $ delay = 0 /* seconds */ , callable $ onError = null ): void
202204 {
203205 gc_enable ();
204206
205207 $ time = 0 ;
206208
209+ if ($ delay > 0 ){
210+ sleep ($ delay );
211+ }
212+
207213 while (! connection_aborted () || PHP_SAPI == 'cli ' ) {
214+
215+ $ suspend = $ sleep ;
216+
208217 try {
218+ $ execStart = \time ();
209219 $ callback ();
220+
210221 } catch (\Exception $ e ) {
211222 if ($ onError != null ) {
212223 $ onError ($ e );
@@ -215,8 +226,11 @@ public static function loop(callable $callback, $sleep = 1 /* seconds */, callab
215226 }
216227 }
217228
218- $ intSeconds = intval ($ sleep );
219- $ microSeconds = ($ sleep - $ intSeconds ) * 1000000 ;
229+ $ execTotal = \time () - $ execStart ;
230+ $ suspend = $ suspend - $ execTotal ;
231+
232+ $ intSeconds = intval ($ suspend );
233+ $ microSeconds = ($ suspend - $ intSeconds ) * 1000000 ;
220234
221235 if ($ intSeconds > 0 ) {
222236 sleep ($ intSeconds );
@@ -226,7 +240,7 @@ public static function loop(callable $callback, $sleep = 1 /* seconds */, callab
226240 usleep ($ microSeconds );
227241 }
228242
229- $ time = $ time + $ sleep ;
243+ $ time = $ time + $ suspend ;
230244
231245 if (PHP_SAPI == 'cli ' ) {
232246 if ($ time >= 60 * 5 ) { // Every 5 minutes
0 commit comments