Execute cron using PHP


summary: I have this system that creates jobs to be finished in given amount of time, could be 4 hours, could be 10 days, depends on the job itself. The client lately asked me to program a feature that would send him an email every time a job is due.

The logic thing to do would be creating a cron that would run only once and then be deleted, such a temporary, one-time-use cron.

Every time a job is filled and sent to the database, a cron will be set up to run one minute before due time of the job ( so if I start a 4-hr job at noon, the cron is set up to be executed at 3.59pm, and be removed right after )
I searched the net to find some solution, to no vail, though. I mean I have found few but they required some extra software to be installed on the server.

So another thing I would do is to create a cron that would run every fifteen minutes or so to look for any jobs that might be due in this 15-min span. This is totally do-able but still I would like to try something fancy ( :slight_smile: ) if it’s even possible.

What do you think?

Any response will be appreciated. Thank you.

Greg Bialowas

So you want an email to be sent when a due date is within x minutes of due date current time? I’m assuming this value is available through a db?

Set a cron to run every minute. Your script will have a lock on a temp file (acquire a write lock on some tmp text file, otherwise exit) to prevent multiple scripts from running at the same time (in case of any type of hang). Query for anything within that x minute range from current time where some bool flag such as ‘notification_sent’ is false. Flip the flag, send the email. Simplicity is the best sophistication.

Your other option is to create a service. PHP isn’t terribly great at running as a service, so I don’t recommend this one.

Thanks Kyle!

Another thing you could do is add jobs to a worker queue like beanstalkd with a delay. For example for that 4 hour job, put in a job in the queue with a delay of 3 * 60 * 60 + 59 * 60 seconds. Then have a worker listen to that queue and send the email when it receives the job.

Here is a nice tutotial on beanstalkd: http://www.lornajane.net/posts/2014/working-with-php-and-beanstalkd