# How to ensure only one cron job running?

**URL:** <https://discourse.cakephp.org/t/how-to-ensure-only-one-cron-job-running/2064>\
**Category:** Need Help\
**Created:** [February 14, 2017, 2:29am UTC](https://discourse.cakephp.org/t/how-to-ensure-only-one-cron-job-running/2064 "2017-02-14T02:29:21Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![littleylv](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/littleylv/32/494_2.png) [@littleylv](https://discourse.cakephp.org/u/littleylv)\
**Post date:** [February 14, 2017, 2:29am UTC](https://discourse.cakephp.org/t/how-to-ensure-only-one-cron-job-running/2064/1 "2017-02-14T02:29:21Z")

</div>

This question maybe is not about cakephp problem but linux etc.

In src/Shell/MyShell.php

```
public function foo(){
    ...
    // In this function, i get some records and then run foreach
    $query = $bar->find()->where($condition);
    foreach ($query as $q) {
        ...
    }
    ...
}

```

crontab

```
*/5 * * * * cd /var/www/html/myapp && bin/cake my foo > /dev/null 2>&1

```

I need to run MyShell::foo per 5 minutes. But this job might last for above 5 minutes.  
That causes this problem: the query in the next cron job may find duplicate records to run but that’s wrong with my business 😕

I google and add the following code in my foo function:

```
    exec("ps -ef | grep 'foo' | grep -v grep | wc -l", $ret);
    if(intval($ret[0]) > 2){
        // Too many processes running
        return;
    }

```

But it did not work always.

Do you guys have any idea to solve it. Thanks.
