始终在bakground中运行单个进程

时间:2015-07-16 00:26:05

标签: php

如何在后台运行流程?

我想创建一个基于数据库信息管理一些工作队列的进程。

我目前正在使用cron作业,我每分钟运行一次cron作业,并且有30次调用,间隔为sleep(2)。虽然这项工作正常,但我不时注意到有竞争条件。

是否可以一直运行相同的过程?我仍然会尝试定期启动cron作业,但如果它看到自己正在运行,它就会关闭。

或者这是一个坏主意?是否存在内存泄漏或其他问题?

2 个答案:

答案 0 :(得分:1)

几年前我不知道MQ系统和nodejs等。 所以我使用这样的代码并添加到cron每分钟运行一次:

<?php 

// defining path to lock file. example: /home/user1/bin/cronjob1.lock
define('LOCK_FILE', __DIR__."/".basename(__FILE__).'.lock');

// function to check if process is running or not
function isLocked() 
{ 
    // lock file exists, but let's check if it's running?
    if(is_file(LOCK_FILE)) 
    { 
        $pid = trim(file_get_contents(LOCK_FILE)); // reading process id from .lock file
        $pids = explode("\n", trim(`ps -e | awk '{print $1}'`)); // running process ids
        if(in_array($pid, $pids))  // $pid exists in process ids
            return true; // it's ok, process running
    } 

    // making .lock file with new process id in it
    file_put_contents(LOCK_FILE, getmypid()."\n" );  
    return false; // previous process was not running
} 

// if previous process locked to run same script
if(isLocked()) die("Already running.\n"); // locked, exiting


// from this point we run our new process
set_time_limit(0);
while(true) {
    // some ops
    sleep(1);
} 

// cleanup before finishing
unlink(LOCK_FILE);

答案 1 :(得分:0)

您可以使用名为forever的内容,该内容需要nodejs

安装节点后,

永远安装:

 $ [sudo] npm install forever -g

永远运行脚本:

forever start app.js