I'm writing a PHP script (OK, it's a daemon worker) that I'd like to run in the background, and it follows the following pseudo-code:
do {
// stuff
sleep(60*30); // 30 minutes
} while(1);
Now, how can I set this baby up to run automatically in the event that the server gets restarted. I don't need to worry about state, since everything is stored in the MySQL DB - and it should just be able to pick up right where it left off.
I'm using an Ubuntu 12.04 x64 server, on AWS (if that matters).
Thanks!
As a solution to your specific problem use bash script to execute PHP cli Pusedo code will be
\usr\sbin\php -q \home\user\myphpscript.php
this will execute the PHP script without any time constrain, however since you use PHP CLI you might not get some environment variables, which are web specific, but for such background process you hardly need them anyways.
Related
I need to keep a php script running and alive on my server, the script runs and checks a DB for record, processes if needed, sleeps for 3 and then loops to the top of the script in an infinite loop. The issue is launching it, if I launch it via terminal (its running on an ubuntu system) using php script.php then if the terminal session is ended the script stops running.
So how can I go about launching the script so that it will remain running in the background.
Furthermore if I set up a cron job that runs once an hour and fires off a different script that check the primary one is still running and if not restarts it, how would I get the this checker script to check that the initial script is still running (even if its in sleep).
Any assistance will be greatly appreciated
If starting the script from the web is an option, then set time limit to "unlimited" (in the script itself):
set_time_limit(0);
and set ignore_user_abort to "true":
ignore_user_abort(true);
Then you can run the script as usual from the web, and it will run forever (until the process is killed or script exits in the usual way).
Of course, you can (and MUST) protect such a starter-script by password, e.g. by using HTTP authentication via .htaccess, so that somebody cannot start many forever-running scripts, which would lay down your server.
On checking whether another process is running, see question1, question2, or try searching "[php] check if process is running" here on StackOverflow. See also http://php.net/manual/en/refs.fileprocess.process.php.
If you want to run it from the terminal and keep it running permanently, look into GNU screen. It's a virtual terminal that keeps running in the background even when you close the terminal.
$ sudo apt-get install screen
With this, you can simply do:
$ screen php myscript.php
The script will load in a screen session which you can disconnect from, and even when you close the terminal it will keep running. To check up on it, simply call:
$ screen -x
Best part is screen is free software and is in the repo of all good distros (and other *NIX's if Linux doesn't float your boat).
Cron Job would be one solution:
More details about Cron job.
Another way to do it is to use Gearman or some other taks managers like in this post
I have a Windows 2012 Server that runs IIS and SQL Server 2012.
I am trying to run a PHP script from the command prompt. The script takes around 1 hour to run. If I run it straight from the command line like this - c:\PHP>php.exe "D:\Web\phpScript.php" it runs fine. Again it takes around 1 hour to run but it completes fine.
The thing is I need to run it from another PHP page. So this code - exec('start c:\php\php.exe "D:\Web\phpScript.php"'); in PHP runs the script. When I run it from PHP like that it runs good for around 30 minutes or so but for some reason Windows ends up killing the process after around 30 minutes.
I have been watching the task manager on Windows and cannot see any difference in the way the process runs compared to when I run it straight from the command prompt or when I use PHP to run the command. They both show up as a background process and look exactly the same in the task manager but for some reason Windows is killing the one that runs from PHP and not the one ran straight from the command prompt.
I have even tried running the PHP one in Realtime thinking maybe if it had higher priority it would not get killed but that did not help.
I am really stuck with this.
Any help would be great.
Thanks!
If it has to do with your PHP configuration, you can force allowing a certain execution time with this at the beginning of the script
set_time_limit(60*60*2); // allows 2 hours execution time
Then to execute the external file just use include('D:\Web\phpScript.php'); in the script.
http://php.net/manual/en/function.set-time-limit.php
Otherwise if its a server problem, beats me. You could, of course...run it in your web browser instead of in the command prompt, if PHP is installed on the machine.
Part of my web application is a background script that polls from a beanstalkd server and process data.
This script needs to run continuously (like a daemon). If it crashes, it needs to be started again. It also can't be started twice (more precisely run twice).
As I want to ease the deployment and development process, I want to avoid using pcntl_fork. It's not available on Windows, it necessitates recompiling PHP on Mac, sometimes on Linux too...
Can I do this simply using a bash script to launch the PHP script in background?
# verify that the script is not already running
...
/usr/bin/php myScript.php &
If I execute this batch with crontab every hour or so, my process should run continuously and be restarted in maximum one hour if it crashes?
Assuming blindly that you control the server(s) on which your scripts run, Supervisor is probably a good solution for you.
It's a process control daemon, written in Python. You can configure it to start your PHP script and keep it running. The PHP script itself doesn't need to do anything special. No forking, no manual process control, nothing.
On the other hand, you've also expressed concern about pcntl_fork not being available on Windows. If you're really running this thing on Windows, Supervisor isn't going to work out for you, as it isn't Windows friendly. Keep in mind that Windows isn't really friendly to Unix-style daemonization either, as it would want to control the daemon as a Service. While that's possible, it's not exactly an easy or elegant solution.
So, ok, I'm using PHP for my website, and suppose I know quite a bit of MySQL and a little bit of MS SQL.
Now, I want to parse some XML with PHP/USD exchange rate and store it in the database.
The simplest way one could think of would be, perhaps this:
$XMLContent=file("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=PHP");
foreach($XMLContent as $line){
$a=&strip_tags($line);
if (is_numeric($a))
{
// output the exchange rate
echo $a;
// THen I would probably go like this:
mssql_query('update table set xchange_rate='.(float)floatval($a));
// break cycle once found;
break;
}
}
That would perfectly do... if it didn't take 0.8 seconds to run this script, due to external XML GET request.
So I suppose I should use Windows Scheduler, and make a task to run, let's say every hour to update the records. Now the question is, I've no idea what script I would use. I mean, I can't just simply run browser with a PHP script - that would be rediculous.
So, what would be the easiest way to make a script/ application to run it outside PHP, without a need to actually open a browser.
Thanks!
EDIT
Good point, right now I'm testing it on Win7, but later it is going to be implemented on Windows Server (2008?).
php has a binary executable interpretor too. On win, its called php.exe
http://php.net/manual/en/features.commandline.php
get it working first from a shell prompt, then make a scheduled task for it.
keep in mind, it is not the same php as you get when running a script through a webserver. Some settings are different, and the version may be different, and may use a different php.ini file(and so may have different extensions loaded).
consider using absolute file paths to start until you get things working.
You don't need a browser to run a PHP script. PHP can happily run as a console application. Without knowing what system you're deploying this on (i.e. which OS), it's hard to give you more directions. For example, on a unix-like system (UN*X, linux, OS X, etc.) you can create your PHP file:
somefile.php
<?php
.....
?>
save this file into some pre-defined directory, for example, /opt/myproject and then schedule it in /etc/crontab (assuming your php is installed in /usr/bin):
7 * * * * /usr/bin/php /opt/myproject/somefile.php
This would run your script with PHP, without any browser, once an hour, at 7 minutes past each hour.
EDIT If you're to deploy this on a windows server, you can either use at command on the command prompt or use the Task Scheduler snap-in in Server Manager to configure your job. The PHP script would be saved where you like it to be (e.g. D:\Projects\MyProject\myfile.php) and the command you would schedule to run would be C:\WAMP\bin\php.exe - or whereve your php.exe is located).
I am working on a site that require a php script running on a server without any request,
it is a bot script that keeps (not full time but at least once a day) checking client accounts and send alert messages to clients when something happens.
any ideas are appreciated.
Assuming you need to do this on linux, you may run any php script from the browser and from the CLI as well.
You may run a simple php script:
<? echo "Ana are mere"; ?>
like this:
php -f ./index.php
Be careful about file-permissions, and any bug that may creep inside your code, memory leaks or unallocated variables will become VERY visible now, as the process will run continuously.
If you dont want it running in the background all the time, take a look at crontab (http://unixgeeks.org/security/newbie/unix/cron-1.html) to be able to start jobs regularly.
-- edit--
take a look at php execute a background process and PHP: How to return information to a waiting script and continue processing
Basically you want to start a background process, and you may do this by either using exec() or fsockopen() or a file_get_contents() on your own script probably in this order, if don't have access to exec, or socket functions.
Also take a look at http://us2.php.net/manual/en/function.session-write-close.php so the "background script" won't "block" the request and http://us2.php.net/manual/en/function.ignore-user-abort.php
Use a cron job to do it http://www.cronjobs.org/
You can automatically call a script at any interval you like indefinitely. Your hosting provider should support them if they are good.
You should also consider putting a unique key on the end of the page
ie. www.yoursite.com/cronjob.php?key=randomstring
and then only run the script if the key is correct, to prevent bots and other users from running the script when you don't want it run.
If you can't create a cron job, then create a page that does what you want and create a scheduled task on another machine (maybe your PC?) that just goes out and hits that page at a certain time every day.
It's really a hack, but if you absolutely can't set up a cron job, it would be an option.
As Evernoob and Quamis said, you want to have a cron job (UNIX/Linux/Mac OS) or a scheduled task (MS Windows). Furthermore, you can either have the PHP script run using the PHP command line interface (CLI), in which case you can invoke the PHP executable and then your script name. As an alternate, you can use a tool like wget (availble on all platforms) to invoke the PHP script as if someone had typed the URL in the location bar of a web browser.
A php script could not be used like you imagine here. Because it's executed through apache after a request from somewhere.
Even if you do while(1) in your script, apache/php will automaticly stop your script.
Responding to your comment, yes you'll need ssh access to do this, except if your web interface allow you to add cronjob.
Maybe you can write a service which can be executed with a program on another server and do the job.
If you have no access to the server the easiest way would probably be to hit it through the browser, but that would require you or an external script hitting the URL at the same interval each day when you wanted it to one. You may also be able to setup a Selenium test suite that runs locally on a schedule and hits the page. I'm not 100% if that's possible with Selenium though, you may need some 3rd-party apps to make it happen.
Something else you could try would be to see about using PHP's Process Control Functions (link). These will let you create a script that is a deamon and runs in the background. You may be able to do this to keep the script running on the server and firing off commands at programmed intervals. You will still need some way to get it running the first time (browser request or via command line) though.