S
S
sindrom2011-02-04 00:16:42
PHP
sindrom, 2011-02-04 00:16:42

PHP: run task in background

What are the most correct and reliable approaches to use if you need to run some long-running task in the background?
I will give an example to make it clearer:
there is a main php script, a controller that processes user actions. The user presses a magic button in the interface, which should start a long-running task and return control to the user. In this case, it is not required to return or somehow additionally process the result of the long script.

I know that for such tasks there are various libraries for creating a message queue, but specifically for my example, this is redundant.
I would also like to do without cron-tasks and other OS-specific things.

Thank you.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
W
WebSpider, 2011-02-04
@sindrom

In my opinion, in your case, the simplest option would be exec:

exec("php /www/site/script.php >>/www/logs/script.log 2>&1 &");

Unfortunately, this will only work in *nix, because on Windows it is not so easy to start a process in the background

J
Jazzist, 2011-02-04
@Jazzist

PHP CLI misbehaves in the background. From what is applied "in haste", BASH, Perl and Python behave well.
In a task where it was necessary to save resources, I did the following:
1. The PHP script saves the “task” in BASH to some job directory
2. Cron every minute runs a dispatcher script written in Perl (there was a viable option in BASH) that looks for N the oldest (by last modified time) scripts from the job directory, and runs them.
3. Run scripts first of all destroy (rm) themselves, so that they will not be executed anyway - after all, they are already loaded into RAM. The results of the work are stored in the FS or in the database, for servicing the interface logic
The number N for each specific server is determined individually - by testing.
There was a "pitfall" that was even discovered at the first time completely at the wrong time - everything that launches cron should work with absolute paths.
Thus, a project like YouTube and a similar one, also converting video, were made.

D
Dmitry, 2011-02-04
@StraNNikk

I also stick with the CRON option.
Personally, I would put the tasks in a table in the database, where the statuses of the tasks would be recorded, and in the crown every minute I would work out a certain script (at least in php, at least on something else), which would check this table, launch new tasks, and delete already completed ones .

@
@molodoy, 2011-02-04
_

As an option: the user presses the button - a php script is launched on the server with an ajax request (with ignore_user_abort).

E
eternals, 2011-02-04
@eternals

1. Agents - run at the end of page generation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question