I'm running a foreach loop in php which takes longer to execute than my maximum execution time of 30 seconds. The loop sends individual emails to users.
Instead of running cron jobs every 30 seconds and creating queues for records is it unethical to just restart the counter in the loop using set_time_limit(30) ?
$i = 0; //start count from 0
foreach ($users as $user):
//limit emails sent
if(++$i == 100) break; //ends execution of loop
set_time_limit(30); //restart timeout counter
send_email($user); //send email to user
endforeach;
I'm new to this but with the code above I think I'm giving each email 30 seconds to complete but also breaking the loop when 100 emails are sent so the script doesn't run forever.
Update: set_time_limit(0) goes against hosting TOS, I believed that restarting the timeout counter restarts the script as well as would CRON
Running set_time_limit in foreach loop with brings and solves few problems at the same time.
I see the greatest pro of this solution in making sure that no request will take more than 30 seconds long (and when you have a full cue I believe it's even desirable to cut every script that takes that long) .
The problem it brings it's that no all jobs will be executed necessarily. Maybe you'll experience some problems in the middle of jobs queue and it will all fail.
I would go with this:
# crontab
0,30 * * * * php /path/to/your/script.php
And would use your script.
If you need to execute jobs as fast as possible, I'd create a bash script that would execute (without any timeout) php script as long as it wouldn't finish with exit(0) (all jobs executed successfully) or wouldn't return "Done!" or whatever you like.
Exampe bash script: 1,2
#!/bin/bash
# Note that false sets $? to 1
false
while [ $? -ne 0 ]; do
php /path/to/your/script.php >> log.log
done
And if you need to make sure no two instances will run at the same time, google one of those (just from the top of my head):
.pid fileLOCK TABLEPS: If you'll use some of the method make sure that your script will work if it crashes in the middle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With