Divyesh Jesadiya
Divyesh Jesadiya

Reputation: 957

run php script exactly every 2 second

i have one php file that i want to run every 2 second for a 1 minute. because in my server i can set min cron for 1 minute only. so i made this script.

<?php
$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    shell_exec('/usr/local/bin/php /usr/local/www/my_file.php');
    time_sleep_until($start + $i + 2);
}
?>

and second option is.

<?php
for ($i = 0; $i <= 59; $i+=2) {
    shell_exec('/usr/local/bin/php /usr/local/www/my_file.php');
    sleep(2);
}
?>

but both of them are not working because my script execution time is 50 to 60 second. so, its not running every 2 second but every 50 to 60 second. so, is there any solution for that to start new script execution every 2 second? i don't have any idea please help me.

Upvotes: 0

Views: 457

Answers (1)

Neodan
Neodan

Reputation: 5252

You can write a bash script which executes your php script every 2 seconds for defined amount. And this bash script can be executed via cronjob.

Example:

#!/bin/bash

count=10

for i in `seq 1 $count`; do
    /bin/php /path/to/scrip.php &
    sleep 2
done

Upvotes: 2

Related Questions