简体   繁体   中英

Show Number of Times a PHP Script is Running via Cron

I have a php script that runs jobs on a server via cron. Basically the cron is run every minute like:

        • php /path/to/my/script/script.php

This script can be run multiple times, and continue to run for some time.

What I am trying to do, is find a way to read the processes running for this user, and count how many times script.php is running. Before the cron is actually run. Basically so that if there are 10 instances of the script running, no other instances of it will start until there are less then 10 running. I need to make sure it doesn't start if there are 10 running.

Hopefully this makes sense. ;)

Reading processes is depends on OS you are using and would not be same. Instead, every time your script run, you can write details to database. Like;

process_name  - run_time - is_completed 

Before script run, you need to check if there is not completed process more than 10 from processes table. You'll also have log records

First you should put the call to your PHP script inside a Shell script.

In this script, the first step would be to count current running instances of your PHP program.

If the count is below the defined limit ( 10 in your case), run a new instance of your PHP program.

Now about how to count the current running instances, you could achieve this using the ps command piped with a grep command (to filter processes) followed by a wc -l command (to do the counting).

Or you could create a unique empty file just before running a new instance, like /tmp/php_script_<timestamp> and delete it when the PHP script is over.

Counting instances would then be equivalent to counting the number of files in /tmp starting with php_script_ (another grep piped with wc -l ).

If you want it to check it with bash script, try combining ps ax with grep :

ps ax | grep 'php /home/janj/www/test.php'

And this will return something similar to this:

17857 ?        Ss     0:00 /bin/sh -c php /home/janj/www/test.php
17858 ?        S      0:00 php /home/janj/www/test.php
17897 ?        Ss     0:00 /bin/sh -c php /home/janj/www/test.php
17898 ?        S      0:00 php /home/janj/www/test.php
17903 pts/7    S+     0:00 grep --color=auto php /home/janj/www/test.php

Combine it with maxime.bochon answer and you will have complete solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM