Created
July 8, 2013 13:27
-
-
Save mudge/5948769 to your computer and use it in GitHub Desktop.
A retry function for PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once dirname(__FILE__) . '/../lib/simpletest/autorun.php'; | |
function retry($f, $delay = 10, $retries = 3) | |
{ | |
try { | |
return $f(); | |
} catch (Exception $e) { | |
if ($retries > 0) { | |
sleep($delay); | |
return retry($f, $delay, $retries - 1); | |
} else { | |
throw $e; | |
} | |
} | |
} | |
class RetryTest extends UnitTestCase | |
{ | |
function testRetryWithNoExceptions() | |
{ | |
$name = "Bob"; | |
$result = retry( | |
function () use ($name) { | |
return $name . "!"; | |
}, | |
0.1 | |
); | |
$this->assertEqual("Bob!", $result); | |
} | |
function testRetryWithException() | |
{ | |
$fail = true; | |
$result = retry( | |
function () use (&$fail) { | |
if ($fail) { | |
$fail = false; | |
throw new Exception("Boom!"); | |
} else { | |
return "Woo!"; | |
} | |
}, | |
0.1 | |
); | |
$this->assertEqual("Woo!", $result); | |
} | |
function testRetryTriesTheExpectedNumberOfTimes() | |
{ | |
$count = 0; | |
try { | |
retry( | |
function () use (&$count) { | |
$count += 1; | |
throw new Exception("Boom!"); | |
}, | |
0.1 | |
); | |
} catch (Exception $e) { | |
} | |
$this->assertEqual(4, $count); | |
} | |
function testRetryWithConstantFailure() | |
{ | |
$this->expectException(new PatternExpectation("/I will never work./")); | |
$result = retry( | |
function () { | |
throw new Exception("I will never work."); | |
}, | |
0.1 | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, I am using a phpmailer.
if a user uploads a material, it sends notices to other users email and i used the phpmailer.
it is working. but when there is an error occurs, it shows an error, i don't want the user to see the error but the code to retrying sending the message.
i need help on how i should integrate your code in it.
or should i post my code here.
`
foreach($result as $row){
$email = $row['email'];
$full_name = $row['full_name'];
$stu_email = $row['stu_email'];
$stu_name = $row['stu_name'];
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
require '../vendor/autoload.php';
`