3

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?

Searock
  • 6,278
  • 11
  • 62
  • 98
smilly92
  • 2,383
  • 1
  • 23
  • 43
  • 2
    cron will be better there is no point of hang the script for 10 mins – Tarun Sep 15 '12 at 05:41
  • Okay can you confirm some things here , Do you want a delay with in the cronJob , I mean , code in the cronjob has to be delayed ? – Aravind.HU Sep 15 '12 at 05:41
  • 2
    A cron job would certainly be a reasonable way of doing it. It'd be practical if your hosting provides cron! Do you need the delay to be exactly n mins? That'd be slightly trickier with cron. If it's just at least n mins you'd be fine. – John Carter Sep 15 '12 at 05:42
  • 2
    It seems like your only options are a LOOONG-running script (which your hosting probably won't allow) or queuing tasks and executing them periodically with cron. – Andrew Sep 15 '12 at 05:43
  • 1
    Caling the Quartz library from PHP might be an option. I don't know much about it (besides the fact that it is a Java library), if it is truly available to call in PHP, or if it uses cron under the covers. – Merlyn Morgan-Graham Sep 15 '12 at 05:45
  • Quartz looks very cool... Probably overkill for my project but. – smilly92 Sep 15 '12 at 05:53

1 Answers1

9

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();
    }
}
napolux
  • 15,574
  • 9
  • 51
  • 70