Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code after a 10 minute delay in PHP

Tags:

php

cron

I need to delay the execution of some code in PHP (for example; sending an email) by 10 minutes after an event (form submission).

What is the best way to accomplish this?

Would be my only option be to run a Cronjob every minute? Is this practical on shared hosting?

like image 958
smilly92 Avatar asked Apr 14 '26 09:04

smilly92


1 Answers

Using cronjobs is the best way.

If you can't use a cronjob on your shared hosting (ask the customer support), you can run a cronjob on a machine connected to the internet (i.e. your home computer) that runs a wget to a php page on your server, authenticate on it and then run the php code to send your email.

For the PHP code part I'll use a database table with all the emails to be sent, a creation_date field and a status field.

Your PHP code called by the job will simply do (in pseudo code):

$batchRecords = takeAbunchOfRecordsWhereStatus(NOT_SENT);
while($batchRecords) {
    if($creationDate + 10 minutes >= now()) {
        sendEmail();
        markRecordAsSent();
    }
}
like image 172
napolux Avatar answered Apr 16 '26 23:04

napolux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!