I have an API endpoint which performs an action based on a user's request, and then echoes a json response. This endpoint also needs to trigger a notification, but only after a 30 second delay. The reason is in case the user reverses their request within that delay (via another endpoint), which would would mean no notification should be sent. Here's the relevant piece of code:
// response
echo json_encode(
array(
'success' => 1,
'updateUser' => $updateUser['ok'],
'updateTarget' => $updateTarget['ok'],
'updateActivity' => $updateActivity['ok']
)
);
// send push notification after delay
sendDelayedNotification($user_id, $target_id);
The sendDelayedNotification
function has sleep(30)
in it to delay its execution. The function then checks if the condition still exists that warrants a notification.
The issue is that even though this function fires after the echo
statement, it delays the response and the request times out. Is there a way to code this so that the response isn't delayed?
Don't do the job in the same script. The response for your php script won't send until the entire script has finished running.
You will need to have a different script to send notifications. Have your response set a database record or create a file or something with the time of the initial request. The notification script would scan the location and send the notifications as appropriate. Your cancel endpoint would delete/modify the record so that the notification script won't execute.
PHP in it's nature is synchronous.
There are few options:
1st_script.php
<?php
echo json_encode(
array(
'success' => 1,
'updateUser' => $updateUser['ok'],
'updateTarget' => $updateTarget['ok'],
'updateActivity' => $updateActivity['ok']
)
);
exec('php 2nd_script.php > /dev/null 2>/dev/null &');
2st_script.php
<?php
sleep(30);
doStuff();
Run second php script as daemon and use something like http://supervisord.org/ to make sure it does not die.
1st_script.php
<?php
echo json_encode(
array(
'success' => 1,
'updateUser' => $updateUser['ok'],
'updateTarget' => $updateTarget['ok'],
'updateActivity' => $updateActivity['ok']
)
);
submitJobToQueue(data);
2nd_script.php - script that supervisord runs.
<?php
while(true) {
$job = getJobOlderThan30Sec();
executeJobQueue($job);
}
OR 2nd_script.php - script that crontab.
<?php
$job = getJobOlderThan30Sec();
executeJobQueue($job);
I've worked with ZendQueue, Gearman and RabbitMQ on large scale projects. Liked Rabbit most. Gearman had some scalability issues. ZendQueue or any other DB based queue would be easiest but it is pull not push system like others.
like http://reactphp.org