I've created a PHP form for my website and have added an email response to it to be sent to the user once they've submitted their details. What I'd like to do is add in a delay of some sort so that the user doesn't immediately receive the email. I'd like to pretend that it's a real person emailing them back instead of them receiving an email 2 seconds after clicking the submit button.
Any ideas how I'd do that?
As long as you're storing the data you need to create the email in a db, you can create a cron job to query for rows that have not been sent yet, send your emails, mark them as sent.
this will wait for 5 minutes.
So that's without the need for db right? And can that be placed anywhere or in specific place in php script?
Using sleep (300) means the user also has to wait for 300 seconds for the request to complete, which surely is not what you want (apart from the fact that PHP will time out after 30 seconds...)
So I would go with the cron solution. Or, you can implement a message queue and give the message a random delay, but that's a lot more involved to implement.
End user sleep aside, this will also create system over head due to processes continuing to run. This is just bad practice in any language.
An exception to this is in a language with concurrency. In Golang I might create a new function and start a new goroutine (sort of like a thread) when the server starts. This threaded function would then check for emails to be sent that were either stored in as shared variables memory (not possible in PHP) or read from a db, then sleep for x amount of time. This would ensure that only one process is running to do this action, not many.
This topic is now closed. New replies are no longer allowed.