如何构建一个带倒计时的mysql排队系统?

时间:2015-06-01 23:12:59

标签: php mysql queue

我正在开发一款浏览器/手机游戏,我正在尝试构建一个系统,在经过一段时间后自动结束排队任务。这是大多数游戏中使用的基本研究方案。

研究A费用100美元,需要1小时才能完成。我是否必须每秒检查处于或超过完成时间的任务并触发事件以清除它们并增加级别编号?有更好的方式或更优化的方式吗?这个想法本身就可以工作但是如果你需要在游戏设计中运行5或6个不同的队列会发生什么?显示我抽象他们足以让他们在一个表中?

如果我的问题看起来有点模糊或不稳定,我道歉。我试图找出从这个概念开始的地方。

1 个答案:

答案 0 :(得分:0)

我对它不太熟悉,但我相信您可以使用websockets或NodeJS来创建回调事件,然后您可以使用PHP套接字服务器调用该回调。这种

您可以完成本教程:http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

<强>步骤

首先,使用websocket.onmessage回调识别消息类型,类似于此应该有效:

websockets.onmessage = function(ev)
{
    var msg = JSON.parse(ev.data); //Assuming you'll encode the message components in JSON with PHP

    if ( msg.type == "research_end" )
    {
        FinishResearch(msg.content); //Assuming that the content element of the JSON array contains the ID of the research
    }
}

其次,让服务器发送实际消息。为了不使这个太复杂或太长,我只是假装sendMessage($msg, $client)是一个向客户端发送消息的函数。

但是,正如教程中所解释的,每个客户端套接字都存储在一个名为$clients的数组中,您必须为每个研究添加某种标识符,以便很容易知道哪个研究属于哪个客户端

现在,这是一个重要的部分。在服务器上会有一个名为$research的变量,其结构如下:

$research['peername'][0]['time'] = 60000
$research['peername'][0]['type'] = 20

您可以通过使用以下命令向websocket服务器发送传出消息来添加研究:

var array = {message: '20', type: 'research', time : '300000'}; //Create the request array

websocket.send(JSON.stringify(msg)); //Send it to the socket server as a json string, decode with json_decode once it arrives

然后,当它到达服务器并被识别为研究请求时,我们调用一个名为doResearch的回调,它带有两个参数

//loop through all connected sockets
foreach ($changed as $changed_socket) { 

    //check for any incomming data
    while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
    {
        $received_text = unmask($buf); // Unmask data
        $msg_array = json_decode($received_text); // Decode the JSON string we sent to the server

        doResearch($msg_array, $changed_socket); // Let's say this function contains all the procedures to do the research

    }

}

doResearch与此类似:

function doResearch($msg_array, $socket)
{
    $name = socket_getpeername($socket, $addr);

    $count = count($research[$name]);
    $research[$name][$count]['time'] = $msg_array['time'];
    $research[$name][$count]['type'] = $msg_array['type'];
}

最后,你必须在主服务器循环中添加这样的条件:

foreach ( $research as $i )
{
    foreach ( $i as $i2 )
    {
        if ( time() <= $i2['time'] )
        {
            $sql->query("INSERT INTO researches('peer', 'researchid') VALUES ('".$i."', '".$i2['type']."')");
            sendMessage('Research type '.$i2['type'].' has finished.', $i2['socket']);
        }
    }
}

然后,这将检查研究是否已完成并将其插入数据库。

希望这有帮助。

相关问题