I've been looking through the answers about running php script in a background and they seem to be spreading in two ways.
Some people suggest using this (or something similar):
/usr/bin/php command >/dev/null 2>&1 &
Other suggest using "at" command:
echo '/usr/bin/php command'| at now
What are the major differences about theese two methods? What are the pros and cons?
What I'm trying to do is when user submits the form, I need to run a few-minutes long script, that should obviously be run in background. I've tried both ways and they both worked for me, but I'm not sure which to pick.
The at command is a scheduler that accepts strings from stdin or files that contain commands to run at particular times. Your example:
echo '/usr/bin/php command'| at now
Is giving the 'at' command your command as a string and scheduling it to be run immediately.
The first method is the the typical way to background a process via the shell:
/usr/bin/php command >/dev/null 2>&1 &
The "> /dev/null" part of that is telling the shell to send the stdout of your command to /dev/null, and the "2>&1" part of that is saying to send the output of stderr of your command to stdout (which then goes to /dev/null). Together, they suppress output. You can actually do that in one step with:
/usr/bin/php command &>/dev/null & # bash
The '&' at the end of that is what tells the shell to background the process.
The pros of using 'at' is the flexability of scheduling your command to be run at other times than now (among other things). Read the man page for it. The cons are that it may not be installed on all systems.
The pros of using & via shells is that there is no overhead on the backgrounding per se. When using 'at' to run a command immediately is kindof overkill, since it involve creating a new process for at, scheduling the command, realizing that it's set to be run now, and then running it in the background. Whereas running the command with "&" in the shell will simply run that command in the background.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With