Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: execute script 5 minutes after first script is run

Tags:

php

mysql

events

I'm making a PHP site, and I would like to have a script (when you click a button) which adds some info to my MySQL database (I can do this part by myself) and it executes a script 5 minutes later. Maybe it's not difficult, but it's hard to google stuff like this.

like image 402
Nyohosud Avatar asked Jan 23 '11 15:01

Nyohosud


People also ask

How long can a PHP script run?

One important aspect of PHP programs is that the maximum time taken to execute a script is 30 seconds. The time limit varies depending on the hosting companies but the maximum execution time is between 30 to 60 seconds.

How PHP scripts are executed?

The first phase parses PHP source code and generates a binary representation of the PHP code known as Zend opcodes. Opcodes are sets of instructions similar to Java bytecodes. These opcodes are stored in memory. The second phase of Zend engine processing consists in executing the generated opcodes.

Does PHP run first?

Pragmatically speaking, this is the typical order: PHP runs first and constructs the page. The browser loads the resulting HTML (any JavaScript found gets executed immediately)


3 Answers

Sleep is a VERY bad idea. Client browser would have to wait 5 minutes to finish request!!!

In my opinion it's not possible to do it like you want to.

You should create another script which queries database and checks if there is new data (and on successful fetch does the job). This script should be run by cron every N minutes.

like image 187
Daimon Avatar answered Nov 27 '22 01:11

Daimon


Pretty tough one. I'd go for something like this:

  1. your original script adds a record to the database, containing its time of execution,
  2. another script contains the action that needs to be taken 5 minutes later - but launches it only if the db record mentioned above contains a timestamp of at least 5 minues ago (hope that's clear enough, I'm having trouble phrasing this)
  3. set crontab to execute the second script every X minutes (perhaps 2).

It won't be 5 minutes EXACTLY, but rather something between 5 and 7 (in case you choose to launch the script every 2 minutes). Would that do?

like image 23
mingos Avatar answered Nov 27 '22 01:11

mingos


You could implement a queue in your database, where you add "commands" to be executed, and also store when to execute this command. Then have a cron job that runs every minute and checks said queue to see if it's time to execute a certain command.

like image 30
Stefan H Singer Avatar answered Nov 27 '22 01:11

Stefan H Singer