Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PHP script in background using Ant

Tags:

php

ant

gearman

At my current employer we use Ant to execute our build scripts, and I need to add a target to our build.xml file that will start up 4 PHP scripts that are Gearman workers in the background, and then stop those scripts once the build is done.

I've looked at the 'parallel' and 'daemons' directives (is that the right word?) but I am not experienced enough with Ant to track down the info I'm missing on how to make sure the script runs in the background.

like image 531
GrumpyCanuck Avatar asked Aug 20 '12 16:08

GrumpyCanuck


People also ask

How to execute PHP script in background?

You can put a task (such as command or script) in a background by appending a & at the end of the command line. The & operator puts command in the background and free up your terminal. The command which runs in background is called a job. You can type other command while background command is running.

How do I stop a PHP script from running in the background?

If you started it in background use ps aux | grep time. php to get PID. Then just kill PID . If process started in foreground, use to interrupt it.


1 Answers

As you're not getting many answers I'll suggest a low tech method that might get you start...

Use an ant exec task to fire off 4 background php processes writing their pid to a file which includes the build number (from environment presumably) to identify it.

Once build is complete run script again with a stop parameter and use the file naming system to find process ids, kill take and delete piddling files. Probably worth you having some sort of stale job cleaner in there too.

Shouldn't be too hard to knock up something that works until you can find a more elegant solution.

Edit:

Is this any good for you:

test.php: (this would be your worker script)

<?php while (true) { echo "Hello world" . PHP_EOL; sleep(5); }

runner.sh:

#!/usr/bin/bash

FILE_TO_RUN=test.php

if [ -z $TEST_RUNNERS ]; then
  TEST_RUNNERS=4;
fi;

if [ -z $BUILD_NUMBER ]; then
  echo "Can not run without a build number";
  exit 1;
fi;

FILE="${BUILD_NUMBER}.run"

if [ -e $FILE ]; then
    while read line;
    do
        echo "Killing process " $line
        kill -9 $line
    done
    echo "Deleting PID file"
    rm -f $FILE
    exit 0
fi  < $FILE

for ((i=1; i<=$TEST_RUNNERS; i++)); do
  echo "Setting up test runner number " $i " of " $TEST_RUNNERS;
  php $FILE_TO_RUN &
  echo "PID number: " $!
  echo $! >> "${BUILD_NUMBER}.run"
done
exit 0
like image 107
Lloyd Watkin Avatar answered Oct 05 '22 21:10

Lloyd Watkin