Skip to content

Instantly share code, notes, and snippets.

@fser
Created July 7, 2014 17:34
Show Gist options
  • Save fser/f29180bc45e453a43b3a to your computer and use it in GitHub Desktop.
Save fser/f29180bc45e453a43b3a to your computer and use it in GitHub Desktop.
asynchronous tests using php
<?php
$dbh = NULL;
try {
$dbh = new PDO("sqlite:/tmp/panel.db");
}
catch(PDOException $e)
{
die ($e->getMessage());
}
$status = array('TODO' => 1,
'DONE' => 2);
<?php
include('db.php');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
function variable_get($name)
{
return 15233;
}
try {
$ctx = $dbh->prepare('INSERT INTO tasks (status, uid, module, function, params) VALUES (?, ?, ?, ?, ?)');
$ctx->execute(array($status['TODO'], rand(2000, 3000), rand(1, 15), rand(1, 5), '{"foo": [1,2,3], "bar": FALSE}'));
$pid = variable_get('pid');
posix_kill($pid, SIGUSR1);
echo "Done!\n";
}
catch (PDOException $e)
{
echo $e->getMessage();
}
<?php
include('db.php');
$dbh->exec('CREATE table tasks
(id INTEGER PRIMARY KEY AUTOINCREMENT,
uid int(12) NOT NULL,
status int(2) NOT NULL,
module int(5) NOT NULL,
function int(5) NOT NULL,
params VARCHAR(255) NOT NULL)');
<?php
include('db.php');
// tick use required as of PHP 4.3.0
declare(ticks = 1);
function do_work($signo)
{
global $dbh, $status;
// $dbh->beginTransaction();
$ctx = $dbh->prepare('SELECT * FROM tasks WHERE status = ? LIMIT 1');
$ctx->execute(array($status['TODO']));
while ($line = $ctx->fetch()) {
// Error ! Todo : log & stuff
if (rand(0, 100) > 60) {
echo "Task {$line['id']}: Failed!!\n";
// $dbh->rollBack();
} else {
echo "Task {$line['id']} Module: {$line['module']} Method: {$line['function']} Params: {$line['params']}\n";
print_r($line);
$up_ctx = $dbh->prepare('UPDATE tasks SET status = ? WHERE id = ?');
$resp = $up_ctx->execute(array($status['DONE'], $line['id']));
// if ($resp)
// $dbh->commit();
// else
// $dbh->rollBack();
}
}
}
pcntl_signal(SIGUSR1, 'do_work');
echo "My pid is : " . posix_getpid() . "\n";
// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);
while (1) {
sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment