在Windows上运行PHP应用程序-守护程序还是cron? [英] Running a PHP app on windows - daemon or cron?

查看:107
本文介绍了在Windows上运行PHP应用程序-守护程序还是cron?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些实施建议。我有一个MYSQL数据库,可以将其远程写入以执行本地处理的任务,并且需要用PHP编写的应用程序,以便在传入这些任务时立即执行这些任务。



但是,当然需要告知我的PHP应用程序何时运行。我曾考虑过使用cron作业,但是我的应用程序是在Windows计算机上。其次,我需要每隔几秒钟不断检查一次,cron只能在每分钟进行一次。



我想写一个PHP守护程序,但是我对它的运行方式有所了解工作,甚至是个好主意!



我希望能得到有关最佳方法的任何建议。

解决方案


I need some implementation advice. I have a MYSQL DB that will be written to remotely for tasks to process locally and I need my application which is written in PHP to execute these tasks imediatly as they come in.

But of course my PHP app needs to be told when to run. I thought about using cron jobs but my app is on a windows machine. Secondly, I need to be constantly checking every few seconds and cron can only do every minute.

I thought of writing a PHP daemon but I am getting consued on hows its going to work and if its even a good idea!

I would appreciate any advice on the best way to do this.

解决方案

pyCron is a good CRON alternative for Windows:

Since this task is quite simple I would just set up pyCron to run the following script every minute:

set_time_limit(60); // one minute, same as CRON ;)
ignore_user_abort(false); // you might wanna set this to true

while (true)
{
    $jobs = getPendingJobs();

    if ((is_array($jobs) === true) && (count($jobs) > 0))
    {
        foreach ($jobs as $job)
        {
            if (executeJob($job) === true)
            {
                markCompleted($job);
            }
        }
    }

    sleep(1); // avoid eating unnecessary CPU cycles
}

This way, if the computer goes down, you'll have a worst case delay of 60 seconds.

You might also want to look into semaphores or some kind of locking strategy like using an APC variable or checking for the existence of a locking file to avoid race conditions, using APC for example:

set_time_limit(60); // one minute, same as CRON ;)
ignore_user_abort(false); // you might wanna set this to true

if (apc_exists('lock') === false) // not locked
{
    apc_add('lock', true, 60); // lock with a ttl of 60 secs, same as set_time_limit

    while (true)
    {
        $jobs = getPendingJobs();

        if ((is_array($jobs) === true) && (count($jobs) > 0))
        {
            foreach ($jobs as $job)
            {
                if (executeJob($job) === true)
                {
                    markCompleted($job);
                }
            }
        }

        sleep(1); // avoid eating unnecessary CPU cycles
    }
}


If you're sticking with the PHP daemon do yourself a favor and drop that idea, use Gearman instead.

EDIT: I asked a related question once that might interest you: Anatomy of a Distributed System in PHP.

这篇关于在Windows上运行PHP应用程序-守护程序还是cron?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆