Execute php script Sequentially and Continuously - php

I have developed a script which should execute continuously and sequentially. Now on creating a cron job for this script, it keeps executing asynchronously.
1) I kept a while loop in script and thought of executing this script once so i used #reboot to execute the script once but if apache craches then this script will not start executing by its own ??
2)Using * * * * * cron it executes this script but creates multi-thread and all cron overlaps on the server eventually.
I have ran out of ideas how to execute a server script continuously and sequentially even if apache server restarts.

You're asking for:
a script which should execute continuously and sequentially
That's the definition of a daemon. You can use upstart to easily create a daemon with your php code.
Here you can find a good article to explain how create a daemon with upstart and node.js (but is easy to adapt to a php script): http://kvz.io/blog/2009/12/15/run-nodejs-as-a-service-on-ubuntu-karmic/

cron is for repeating jobs on a timed basis (min interval: 1 minute). It's intended for scripts that eventually exit and need to be restarted from scratch. Sounds like your script is essentially trying to be a daemon - started once, then left running permanently.
Instead of cron to repeatedly start new copies of the script, simply start your script ONCE via an init script, e.g. /etc/rc.local

There are some ideas to deal with checking if a script is running in this question, and you could have a cron run every couple of minutes to ensure its running and starting it if not.

Related

How to create and start an infinite background script in php?

I want to create a PHP script that will run non stop and execute some instructions every minute/hour (according to my need). It should never die.
How should I proceed to this one? How do I start the script itself?
What Iv'e done so far is created an infinite for loop and checking the time and if it's a new minute then calling my function. But when I call the link, it shows my browser is busy.
I want the script to run on Google Compute Engine without any need to call the URL from a second computer. I want something like android foreground service but for PHP.
Cron job is the answer.
Cron is basically a job scheduling daemon. It runs in the background and is executed automatically. You can set it to run at any time that you wish to. This nature of cron makes it useful for automating tasks.
A cron job, is a task which we carry out with the help of a cron.
So if you run a php script with the help of a cron, it'll run on the background. We don't need to run any infinite loops in the script. You can also set a cron job to run at specific time. How it is run and when it is run is totally upto how you configure the cron job. For that you have to edit the crontab file. A cron tab file is a text file containing a list of commands meant to be run at specified times and the commands in the crontab file along with their run times are checked by the cron daemon, which executes them in the system background.
Now, to create or edit entries in your own cron tab file:
$ crontab -e
Add an entry in the crontab file. One thing you have to remember is, for executing php scripts, use the php executable and call the php script from your crontab as shown in the example below
*/2 * * * * /usr/bin/php /var/www/html/project/cron-file.php
This reference might be helpful to you.
Hope this answer helps.
For Unix-system, best practice for such tasks is using Cron: https://en.wikipedia.org/wiki/Cron
Not only for PHP, but any periodical tasks.

How to make php work forever without cron?

Is there a way to make php work forever without cron.
What I want it for is to unban users after a few hours by running a mysql query, thanks
If you don't have access to cron jobs on your server (I guess you are running on a shared hosting?), the best alternative is to run an "external cron". Have a look at www.setcronjob.com. I have been using this for a couple of months now and it is pretty stable.
You can set it up such that it calls a script on your website every whenever you want. (Example: http://www.yoursite.com/script.xxx)
In the script, you can run a MySQL query to check which users have been banned for a couple of hours and then unban them.
You can start your script from the command line and let it run in the background. You will have to design this script in such a way that it never exits and just loops forever using the sleep() function to avoid unnecessary processor load. Since php scripts invoked from the command line have no max execution time the script will run until you manually kill it off with the kill command.
Once you've written the script you can start it with:
nohup php myscript.php &
nohup makes the script still run once you log out of the console session that you started it from, otherwise it would kill off then. The & symbol at the end starts the script as a new process in the background so that you can continue using the console.

Running Cron jobs in parallel (PHP)

In the past, I ran a bunch of scripts each as a separate cron job. Now I'd like to run a controller script with one cron job, then have that call the scripts separately (and in parallel, all at the same time), so I don't have to create a new cron job every time I add another script.
I looked up pcntl_fork() but we don't have that installed. Can fsockopen() do this as well?
A few questions:
I saw this example, http://phplens.com/phpeverywhere/?q=node/view/254, that uses fsockopen(). Will this allow me to run PHP scripts in parallel? Note, the scripts don't interact, but I would still like to know if any of them exited prematurely with an error.
Secondly the scripts I'm running aren't externally accessible, they are internal only. The script was previously run like so: php -f /path/to/my/script1.php. It's not a web-accessible path. Would the example in #1 work with this, or only web-accessible paths?.
Thanks for any advice you can offer.
You can use proc_open to run multiple processes without waiting for each process to finish.
You will have a process handle, you can terminate each process at any time and you can read the standard output of each process.
You can also communicate via pipes, which is optional.
Passing 1st param php /your/path/to/script.php param1 "param2 x" means starting a separate PHP process.
proc_open (see Example #1)
Ultimately you will want to use an infinite while loop + usleep (or sleep) to avoid maxing out on the CPU. Break when all processes finish, or after you killed them.
Edit: you can know if a process has exited prematurely.
Edit2: a simpler way of doing the above is popen
Please correct me if I'm wrong, but if I understand things correctly, the solution Tiberiu-Ionut Stan proposed implies that starting the processes with proc_open and waiting for them to finish will not be run as a cron script, but is part of a running program/service, right?
As far as I understand the cron jobs, the controller script user920050 was thinking of using would be started by cron on a schedule and each new instance would launch the processes all over again, do the waiting for them to finish and probably run in parallel with other cron-launched instances of the controller script.

Monitoring php Scripts through Gearman

I am trying to run my php scripts in Gearman worker code but also want to monitor
besides that if they are taking more than the expected run time ,I want to kill those scripts.Each script has to run in a timely fashion(say running every 10 minutes) and the Gearman client picks ,the script which are ready to run and send s them to Gearman worker.
I tried using the following options :
1) Tried using an independent script,a normal php script which monitors the running process.
But this normal scripts will not inform Gearman that job got killed and Gearman thinks that the job that got killed is still running.
So that made me think I have to synchronize the process of monitoring and process of running php scripts in the same worker.
Also these jobs need to be restarted and the client takes care of them.
2) I am running my php scripts using the following command :
cd /home/amehrotra/include/core/background;php $workload;(this is blocking does not go to the next line until the script finishes execution).
I tried using exec , but exec does not execute the scripts
exec ("/usr/bin/php /home/amehrotra/include/core/background/$workload >/dev/null &");
3) Tried running 2 workers ,one for running php script another for monitoring but Geraman client does not connect to two workers.
Not the coolest plan, but try to use database as central place where everything is controlled.
It will take some resources and time for your workers but it is the cost to make it manageable.
Worker will need to check for commands (stop/restart) that are assigned to him via db. and he can also save some data into db so you can see what is happening.

Does a cron job kill last cron execution?

I have a cron job the executes a PHP script. The cron is setup to run every minute, this is done only for testing purposes. The PHP script it is executing is designed to convert videos uploaded to the server by users to a flash format (eg... .flv). The script executes fine when manually doing it via command line, however when executing via cron it starts fine but after one minute it just stops.
It seems that when the next cron is executed it "kills" the last cron execution.
I added the following PHP function:
ignore_user_abort(true);
In hopes that it would not abort the last execution, I tested setting the cron to run every 5 minutes, which works fine, however a conversion of a video may take over 5 minutes so I need to figure out why its stoping when another cron is executed.
Any help would be appreciated.
Thank you!
EDIT:
My cron looks like:
*/1 * * * * php /path_to_file/convert.php
I don't think cron kills any processes. However, cron isn't really suitable for long running processes. What may be happening here is that your script tramples all over itself when it is executed multiple times. For example, both PHP processes may be trying to write to the same file at the same time.
First, make sure you not only look in the php error log but also try to capture output from the PHP file itself. E.g:
*/1 * * * * * php /path/to/convert.php & >> /var/log/convert.log
You could also use a simplistic lockfile to ensure that convert.php isn't executed multiple times. Something like:
if (file_exists('/tmp/convert.lock')) {
exit();
}
touch('/tmp/convert.lock');
// convert here
unlink('/tmp/convert.lock');
cron itself won't stop a previous instance of a job running so, if there's a problem, there's almost certainly something in your PHP doing it. You'll need to post that code.
No, it will not. You can keep a second process from running by creating a lock file that the script checks for on each run. If the file exists, it does not run. This should also, if appropriate, be used in conjunction with a maximum execution time so that one process does not stall future executions indefinitely. The lock file can just be an empty plain text file called /tmp/foo.lock.

Categories